gpt4 book ai didi

具有通用闭包参数的 Swift 函数

转载 作者:行者123 更新时间:2023-11-30 11:17:27 25 4
gpt4 key购买 nike

我有家长类和 child 类:

class Animal {
func write(_ block: ((_ animal: Animal) -> Void) ) throws {
block(self)
}
}

class Dog: Animal {
var name: ""
}

我需要使用write函数更改名称。现在我这样做:

let dog = Dog()
dog.write { ($0 as! Dog).name = "Bob" }

但我想这样做(不修改Dog):

dog.write { $0.name = "Bob" }

如何做到这一点?

最佳答案

基本上,您需要 block 参数来依赖于调用该方法的对象的类。实现此目的的一种方法是使用使用 Self 的协议(protocol):

protocol Writable { }

extension Writable {
// Self can be used in protocols, and point to the concrete implementation
// of the protocol
func write(_ block: ((Self) -> Void) ) throws {
block(self)
}
}

// Just need to declare the conformance, all subclasses will inherit it
class Animal: Writable { }

class Dog: Animal {
var name = "Unnamed"
}

let dog = Dog()
print("Dog name:", dog.name)
try dog.write { $0.name = "Bob" }
print("Dog name:", dog.name)

正如预期的那样,上面的代码将打印

Dog name: Unnamed
Dog name: Bob

请注意,write 不是协议(protocol)要求的一部分,您可以将其添加到协议(protocol)方法列表中,但是使用 Self 作为协议(protocol)要求的一部分会受到限制可以使用协议(protocol)的地方(集合、非泛型函数参数等)。

关于具有通用闭包参数的 Swift 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51609604/

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