gpt4 book ai didi

swift - 惰性变量的类型推断

转载 作者:搜寻专家 更新时间:2023-11-01 05:42:52 25 4
gpt4 key购买 nike

我有一个惰性变量声明如下:

private lazy var cachedTonesByChord: [Note: [Note]] = self.tonesByChord()

...其中 self.tonesByChord() 具有以下签名:

() -> [Note: [Note]]

现在,当我删除类型时:

private lazy var cachedTonesByChord = self.tonesByChord()

...编译器提示:

Use of unresolved identifier 'self'

为什么编译器不能自动推断类型?

最佳答案

来自 The Swift Programming Language:

If a stored property’s default value requires some customization or setup, you can use a closure or global function to provide a customized default value for that property. Whenever a new instance of the type that the property belongs to is initialized, the closure or function is called, and its return value is assigned as the property’s default value.

您想使用实例方法来设置属性的值,而不是全局函数,但这是不可能的,因为

If you use a closure to initialize a property, remember that the rest of the instance has not yet been initialized at the point that the closure is executed. This means that you cannot access any other property values from within your closure, even if those properties have default values. You also cannot use the implicit self property, or call any of the instance’s methods.

所以,这里的问题是您正在调用自己的方法。

更新转念一想这似乎很奇怪,因为您已经声明了一个 lazy 属性,该属性将在您的实例已经存在时创建。

关于swift - 惰性变量的类型推断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26462193/

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