Self
可以用作方法的返回类型:
func doSomething() -> Self {}
是否可以像这样将Self
用作通用类型?
func doSomething() -> Wrapper<Self> {}
例子
如果我可以对ChristmasPresent进行子类化,并让它具有一个wrapped
函数,该函数返回一个WrappedPresent,其中泛型设置为子类的任何内容,那将是很好的。
class ChristmasPresent {
func wrapped() -> WrappedPresent<Self> {
return WrappedPresent(present: self)
}
}
class WrappedPresent<T: ChristmasPresent> {
var present: T
init(present: T) {
self.present = present
}
}
class ToyCar: ChristmasPresent {}
let wrappedToyCar = ToyCar().wrapped() // Inferred to be: WrappedPresent<ToyCar>
Wrapper<T:class>
,我们可以返回Wrapper<self.dynamicType>
,也许... - cmyr