更新:由于
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是多态的.但是,例如,您无法创建由两个不同类组成的数组.虽然该类可能允许某个初始化程序,但我们无法事先知道它的子类将会.
原文链接:https://www.f2er.com/swift/320102.html解决方案是使用类名本身.这是一个struct Thing的例子:
extension Thing { static func makeTwo() -> (Thing,Thing) { return (Thing(),Thing()) } }