gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 05:20:52 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com