gpt4 book ai didi

swift - 如何在快速协议(protocol)中使这个可设置的属性起作用

转载 作者:行者123 更新时间:2023-11-28 07:01:47 25 4
gpt4 key购买 nike

我在 Playground 上有这段代码:

protocol SettableName {
var name: String {get set}
}

struct SettableNameImpl: SettableName {
var actualName: String?
var name: String {
get {
if let name = actualName {
return name
} else {
return ""
}
}
set (newName) {
self.actualName = newName
}
}
}

struct Something {
var settable: SettableName

func setName(name: String) {
settable.name = name <-- "cannot assign to result of this expression"
}
}

我在 setName 方法中收到“无法分配给此表达式的结果”。我这辈子都无法理解这是为什么。

最佳答案

通过更改 Something 中可设置的名称属性,您正在更改 Something 本身的值,这就是为什么 mutating 关键字必须放在 setName 之前功能。希望我说得足够清楚。

struct Something {

var settable: SettableName

mutating func setName(name: String) {

settable.name = name // "error is gone now"
}
}

关于swift - 如何在快速协议(protocol)中使这个可设置的属性起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31853095/

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