似乎无法使用惰性变量来实现协议(protocol)所需的变量。例如:
protocol Foo {
var foo: String { get }
}
struct Bar: Foo {
lazy var foo: String = "Hello World"
}
编译器提示 Type 'Bar' does not conform to protocol 'Foo'
.
也无法添加 lazy
协议(protocol)声明中的关键字,从那以后你得到 'lazy' isn't allowed on a protocol requirement
错误。
所以这根本不可能吗?
最佳答案
引用 the Language Guide - Properties - Lazy Stored Properties [强调我的]:
A lazy stored property is a property whose initial value is not calculated until the first time it is used.
即,该值在第一次使用时发生了变化。由于 foo
已在 Foo
协议(protocol)中作为 get
蓝图,隐式 nonmutating get
,值类型 Bar
没有用它的 lazy
属性 foo
来实现这个 promise ,这是一个带有 mutating
getter 的属性。
将 Bar
更改为引用类型将允许它实现 Foo
蓝图(因为改变引用类型的属性不会改变类型实例本身):
protocol Foo {
var foo: String { get }
}
class Bar: Foo {
lazy var foo: String = "Hello World"
}
或者,在 Foo
的 foo
属性的蓝图中指定它有一个 mutating
getter。
protocol Foo {
var foo: String { mutating get }
}
struct Bar: Foo {
lazy var foo: String = "Hello World"
}
有关 getter 和 setter 的 mutating
/nonmutating
说明符的更多详细信息,请参阅以下问答:
关于Swift:将协议(protocol)变量实现为惰性变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48062353/