Swift:将协议(protocol)变量实现为惰性变量?

标签 swift lazy-evaluation

似乎无法使用惰性变量来实现协议(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"
}

或者,在 Foofoo 属性的蓝图中指定它有一个 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/

相关文章:

ios - Swift 中关联类型的协议(protocol)问题

r - 使用字符串变量在 R 函数内部传递多个变量信息

swift - 在 Swift Playground 中调试断点?

swift - 如何在 RealityKit 中与 3D 对象交互

ios - 应用程序卸载/重新安装后 CoreData + Cloudkit fetch() 不返回任何结果

scala - 在 Scala 中可以尝试懒惰还是热切吗?

javascript - 如何在 JavaScript 中交换二维数组中的两个元素? (对我从 Chrome 中的 console.log 看到的内容感到困惑)

Haskell 延迟卸载

r - 为什么惰性求值不会破坏这段代码?

ios - 自定义 MKAnnotation 标注 View ?