swift – ‘Self’仅在协议中可用或作为类方法的结果
发布时间:2020-12-14 05:46:46 所属栏目:百科 来源:网络整理
导读:更新:由于 SE-0068 – Expanding Swift Self to class members and value types,Swift 3允许使用其他类型的Self. 您可以从类函数返回“Self”: extension NSObject { class func makeOne() - Self { return self() }} 所以你可以这样做: let set : NSCoun
更新:由于
SE-0068 – Expanding Swift Self to class members and value types,Swift 3允许使用其他类型的Self.
您可以从类函数返回“Self”: extension NSObject { class func makeOne() -> Self { return self() } } 所以你可以这样做: let set : NSCountedSet = NSCountedSet.makeOne() 但是,以下两个不编译: extension NSObject { class func makeTwo() -> (Self,Self) { return (self(),self()) } class func makeMany() -> [Self] { return [self(),self(),self()] } } 错误是: <REPL>:11:34: error: 'Self' is only available in a protocol or as the result of a class method; did you mean 'NSObject'? class func makeTwo() -> (Self,Self) { ^~~~ NSObject <REPL>:11:40: error: 'Self' is only available in a protocol or as the result of a class method; did you mean 'NSObject'? class func makeTwo() -> (Self,Self) { ^~~~ NSObject <REPL>:15:35: error: 'Self' is only available in a protocol or as the result of a class method; did you mean 'NSObject'? class func makeMany() -> [Self] { ^~~~ NSObject 有没有人知道有什么方法可以声明类函数返回类本身的多个实例?
我怀疑,问题在于自我是模棱两可的;它意味着“这个类或子类,无论我们被称为什么时发生的事情”.换句话说,Self是多态的.但是,例如,您无法创建由两个不同类组成的数组.虽然该类可能允许某个初始化程序,但我们无法事先知道它的子类将会.
解决方案是使用类名本身.这是一个struct Thing的例子: extension Thing { static func makeTwo() -> (Thing,Thing) { return (Thing(),Thing()) } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容