
Type of ‘self’ in Swift
In Swift, we have the following types of ‘self’ keyword
- Postfix self
- Prefix self
- Self (uppercase S)
- self (lowercase s)
Postfix .self:
The postfix .self
, refers to the metatype type of the type on which it is called.
In this case, AnyClass.self returns AnyClass itself, not an instance of AnyClass. And SomeProtocol.self freturns SomeProtocol itself, not an instance of a type that conforms to SomeProtocol at runtime. A very common example, we create a subclass of UITableViewCell/UICollectionViewCell (say BaseCollectionViewCell)
class BaseCollectionViewCell: UICollectionViewCell {....}
then for UICollectionView cell registration, we use
yourCollectionView.register(BaseProductCollectionViewCell.self, forCellWithReuseIdentifier: "cellIdentifierProduct")
Prefix self:
In other programming languages call it this and it refers to the instance of the enclosing type. You use it, either explicitly or implicitly, when referring to members of the enclosing type.
Example:
struct Person {
let name: String
init(name: String) {
self.name = name // here self refering member of enclosing type. In Swift it is not mandatory to use self.
}
}
Self (uppercase S):
When used with a capital S, Self refers to the type that conforms to the protocol, e.g. String or Int.
Example:
extension BinaryInteger {
func squared() -> Self {
return self * self
}
}
In the example above, Int
conforms to BinaryInteger
, so when called on Int
the method returns an Int
.
another example
extension SomeProtocolName where Self: UIView
{
func someFunction() {
self.layer.shadowColor = UIColor.red.cgColor
}
}
self (lowercase s):
When used with a lowercase S, self refers to the value inside that type.
extension BinaryInteger {
func squared() -> Self {
return self * self
}
}
In the above example were called on an Int
storing the value 10 it would effectively be 10*10