首页 > swift 中self Self

swift 中self Self

Question: What difference between 'self' and 'Self'? How do I use "Self" in a function implementaion When I define a function in a superclass to return subclass's type?

Description:

class ZKCodingModel: NSObject{


func filterSelf() -> Self {
    // How do I write to return ZKCodingModel's subclass type?   }
}

}

class ZKSubclass: ZKCodingModel {
}

let sub = ZKSubclass()
//I want to call superclass's method to return subclass' type (ZKSubclass)
let filterdSub = sub.filterSelf()


'Self' is the type of a protocol/class/struct/enum.And the 'self' is a instance of a class/struct/enum.As for your requirement,maybe you could write like this:

class ZKCodingModel: NSObject{
    
    func filterSelf() -> Self {
        let result = self.dynamicType.init()
        return result
    }
    
    required override init() {
        
    }
}

class ZKSubclass: ZKCodingModel {
}

let sub = ZKSubclass()
//I want to call superclass's method to return subclass' type (ZKSubclass)
let filterdSub = sub.filterSelf()
print(filterdSub)

output: <__lldb_expr_35.ZKSubclass: 0x7fdc78e0c2a0>

【热门文章】
【热门文章】