首页 > 解决方案 > 具有惰性属性的 Swift 协议 - 不能对不可变值使用变异 getter:'$0' 是不可变的

问题描述

目标:创建一个协议,允许对符合协议的结构的属性进行延迟计算,然后为这些结构的数组添加属性。计算是密集的,应该只执行一次,因此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,但这不适用于代码的其他部分。

我想要达到的目标有可能吗?

标签: swiftprotocolslazy-loading

解决方案


从错误消息中可以看出,$0它是不可变的,因此您不能在其上使用 mutating 成员。

因此,您不能直接迭代bars。您可以做的是遍历它的indices,因为我们知道它bars[$0] 可变的:

print(bars.indices.map { bars[$0].footype }.reduce(0.0, +))

推荐阅读