Swift: 将协议变量实现为惰性变量?
Swift: implement a protocol variable as a lazy var?
似乎无法使用惰性变量来实现协议所需的变量。例如:
protocol Foo {
var foo: String { get }
}
struct Bar: Foo {
lazy var foo: String = "Hello World"
}
编译器抱怨 Type 'Bar' does not conform to protocol 'Foo'
.
也不可能在协议声明中添加 lazy
关键字,因为那样你会得到 '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
协议中被设计为 get
,隐含地 nonmutating get
,值类型 Bar
没有履行其 [=17= 的承诺] 属性 foo
, 一个 属性 和一个 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 和设置器的 mutating
/nonmutating
说明符的更多详细信息,请参阅以下问答:
似乎无法使用惰性变量来实现协议所需的变量。例如:
protocol Foo {
var foo: String { get }
}
struct Bar: Foo {
lazy var foo: String = "Hello World"
}
编译器抱怨 Type 'Bar' does not conform to protocol 'Foo'
.
也不可能在协议声明中添加 lazy
关键字,因为那样你会得到 '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
协议中被设计为 get
,隐含地 nonmutating get
,值类型 Bar
没有履行其 [=17= 的承诺] 属性 foo
, 一个 属性 和一个 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 和设置器的 mutating
/nonmutating
说明符的更多详细信息,请参阅以下问答: