更新:由于
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()) } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。