gpt4 book ai didi

ios - 为什么我不能在 Swift 中使用 let in 协议(protocol)?

转载 作者:IT王子 更新时间:2023-10-29 04:58:35 25 4
gpt4 key购买 nike

我对 Swift 中关于 var关键字 { get set } 的使用的协议(protocol)有疑问。

来自 Apple documentation :

If a protocol requires a property to be gettable and settable, that property requirement cannot be fulfilled by a constant stored property or a read-only computed property. If the protocol only requires a property to be gettable, the requirement can be satisfied by any kind of property, and it is valid for the property to be also settable if this is useful for your own code.

Property requirements are always declared as variable properties, prefixed with the var keyword. Gettable and settable properties are indicated by writing { get set } after their type declaration, and gettable properties are indicated by writing { get }.

我不明白为什么我不能使用let。协议(protocol)中只有 getvar 不只是 let 吗?

像这样:

protocol someProtocol 
{
var someProperty: String { get }
}

这不仅仅是:

protocol someProtocol 
{
let someProperty: String
}

我错过了什么?

最佳答案

“只有 get 的协议(protocol)中的 var 不只是 let?” 不。let 表示常量。但这里不是这种情况。请考虑以下事项:

protocol SomeProtocol {
var someProperty: String { get }
}

class SomeClass : SomeProtocol {

var someProperty: String = ""

func cla () {
someProperty = "asd"
}
}

let someInstance = SomeClass()

print(someInstance.someProperty) // outputs ""
someInstance.cla()
print(someInstance.someProperty) // outputs "asd"

该协议(protocol)指定符合类向外部显示的内容 - 一些名为 somePropertyString 类型的属性,您至少可以获取。

如果协议(protocol)指定了 { get },您的类可以通过 let someProperty: String = "" 选择符合,但它同样可以通过上述代码选择符合。另一方面,如果协议(protocol)指定了 { get set },则您不能在实现中使用 let,但也必须使其可设置。

协议(protocol)不能简单地定义一个值必须是常量——也不应该,这是一个实现细节,必须由实现它的类/结构来处理(或决定)。

关于ios - 为什么我不能在 Swift 中使用 let in 协议(protocol)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34385897/

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