gpt4 book ai didi

swift - 在 Swift 中引用自己的类型?

转载 作者:可可西里 更新时间:2023-11-01 02:06:44 25 4
gpt4 key购买 nike

在类中,声明闭包参数时如何引用类本身?

在下面的例子中,用什么类型来代替Self,这样在构造Foo时,闭包参数也变成了Foo并且AnotherFoo 是否类似?

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
// ...
})
}

最佳答案

我不认为 Swift 允许你做你想做的事,但你可以接近。

使用 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 {
// ...
}
})
}

关于swift - 在 Swift 中引用自己的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42355852/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com