Distinction in Swift between uppercase "Self" and lowercase "self"
Self
can also be used in classes, and is useful. Here is an article about it.
Here is an example. You have a class called MyClass
. MyClass
have methods returning instances of it. Now you add a subclass of MyClass
called MySubclass
. You want these methods to return instances of MySubclass
instead of MyClass
. The following code shows how to do it. Note that the methods can be either instance methods or class methods.
class MyClass: CustomStringConvertible {
let text: String
// Use required to ensure subclasses also have this init method
required init(text: String) {
self.text = text
}
class func create() -> Self {
return self.init(text: "Created")
}
func modify() -> Self {
return type(of: self).init(text: "modifid: " + text)
}
var description: String {
return text
}
}
class MySubclass: MyClass {
required init(text: String) {
super.init(text: "MySubclass " + text)
}
}
let myClass = MyClass.create()
let myClassModified = myClass.modify()
let mySubclass = MySubclass.create()
let mySubclassModified = mySubclass.modify()
print(myClass)
print(myClassModified)
print(mySubclass)
print(mySubclassModified)
The following line printed out:
// Created
// modifid: Created
// MySubclass Created
// MySubclass modifid: MySubclass Created
Self
refers to the type of the current "thing" inside of a protocol (whatever is conforming to the protocol). For an example of its use, see Protocol func returning Self.
The official docs I've found for Self
is in Protocol Associated Type Declaration in The Swift Programming Language. It surprisingly is not documented in the sections on protocols or on nested types:
However, now there is a paragraph about Self Type
including a code example in the official Swift Programming Language's chapter about Types