Update:Swift 3 许可Self
可以从其他类型中使用,感谢SE-0068 – 将 Swift 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(), 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())
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)