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

前端 未结 6 1036
心在旅途
心在旅途 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条回答
  •  盖世英雄少女心
    2020-12-07 11:35

    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
    

提交回复
热议问题