【发布时间】:2019-10-13 14:39:32
【问题描述】:
目标:创建一个协议,允许对符合协议的结构的属性进行延迟计算,然后为这些结构的数组添加属性。计算量很大,应该只执行一次,因此需要lazy。
所以,经过大量阅读(例如:Swift Struct with Lazy, private property conforming to Protocol)和反复试验(请不要将其标记为重复,除非它确实解决了这种确切的情况),我想出了一些可行的方法:
import Foundation
protocol Foo {
var footype: Double { mutating get }
func calculateFoo() -> Double
}
struct Bar: Foo {
private lazy var _footype: Double = {
let value = calculateFoo()
return value
}()
var footype: Double {
mutating get {
return _footype
}
}
func calculateFoo() -> Double {
print("calc")
return 3.453
}
}
在 Playground 中测试:
var bar = Bar()
print(bar.footype)
print(bar.footype)
输出是:
calc
3.453
3.453
到目前为止,一切都很好。
现在,我想创建一个 Bar 数组并添加 footype 属性:
var bar1 = Bar()
var bar2 = Bar()
var bar3 = Bar()
var bars = [bar1, bar2, bar3]
print(bars.map { $0.footype }.reduce(0.0, +))
这给了我以下错误:
不能对不可变值使用可变 getter:'$0' 是不可变的
找到了很多关于这个错误的信息,但我被困住了如何解决它。一种方法是使用class 而不是struct,但这不适用于代码的其他部分。
我想达到的目标有可能吗?
【问题讨论】:
标签: swift protocols lazy-loading