在类中时,如何在声明闭包参数时引用类本身?
在下面的示例中,代替Self
放置什么类型,以便在构建Foo
时,闭包参数也变为Foo
,AnotherFoo
同样如此?< / p>
class FooBase {
init(completionHandler: (_ myself : Self)) {
// ...
self.completionHandler = completionHandler
}
var completionHandler : ((_ :Self) -> Void)?
func strategyMethod() { ... }
}
class Foo : FooBase {
// ...
override func strategyMethod() {
// do stuff
completionHandler?(self)
}
}
class AnotherFoo : FooBase {
// ...
override func strategyMethod() {
// do other stuff
completionHandler?(self)
}
}
func useFoos {
let foo = Foo(completionHandler: {(me : Foo) in
// ...
})
let anotherFoo = AnotherFoo(completionHandler: {(me : AnotherFoo) in
// ...
})
}
答案 0 :(得分:1)
我认为斯威夫特不会让你做你想做的事,但你可以接近。
使用FooBase作为类型,但是在传递给init函数的闭包中,强制转换为您知道参数的类型:
class FooBase {
init(completionHandler: @escaping (_ myself : FooBase) -> Void) {
// ...
self.completionHandler = completionHandler
}
var completionHandler : ((_ myself:FooBase) -> Void)?
func strategyMethod() {
}
}
class Foo : FooBase {
// ...
override func strategyMethod() {
// do stuff
completionHandler?(self)
}
}
class AnotherFoo : FooBase {
// ...
override func strategyMethod() {
// do other stuff
completionHandler?(self)
}
}
func useFoos() {
let foo = Foo(completionHandler: {(myself_in : FooBase) in
// This cast should always succeed when the closure is used as intended
if let myself = myself_in as? Foo {
// ...
}
})
let anotherFoo = AnotherFoo(completionHandler: {(myself_in : FooBase) in
// This cast should always succeed when the closure is used as intended
if let myself = myself_in as? AnotherFoo {
// ...
}
})
}