Distinction in Swift between uppercase “Self” and lowercase “self”

前端 未结 6 1037
心在旅途
心在旅途 2020-12-07 10:53

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

6条回答
  •  猫巷女王i
    2020-12-07 11:39

    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_543
    • self - https://docs.swift.org/swift-book/ReferenceManual/Expressions.html
    • Both - https://medium.com/the-traveled-ios-developers-guide/swift-keywords-v-3-0-1-f59783bf26c

提交回复
热议问题