While playing in a Swift playground I noticed that Self, with capital \"S\", is available along with the lowercase self. Is there any difference be
I think this question could use a simpler answer, more focussed on the difference between Self and self, and perhaps aimed at people newer to Swift.
self - explicit reference to the current type or instance of the type in which it occurs.class MyClass {
func showClass() {
print("\(self)")
}
}
let someClass = MyClass()
someClass.showClass()
// prints "MyClass"
Self - Used specifically in protocol and extension declarations to refer to the eventual type that will conform to the protocol.protocol MyProtocol {
static func returnSelf() -> Self
}
class MyClass: MyProtocol {
// define class
}
MyClass.returnSelf()
// returns MyClass
The difference is that self is used in types and instances of types to refer to the type that it's in; and Self is used in protocols and extensions where the actual type is not yet known.
In even simpler terms, self is used within an existing type; Self is used to refer to a type that Self is not yet in.
Read more here:
Self - https://docs.swift.org/swift-book/ReferenceManual/Declarations.html#//apple_ref/doc/uid/TP40014097-CH34-XID_543self - https://docs.swift.org/swift-book/ReferenceManual/Expressions.html