gpt4 book ai didi

ios - 扩展中的延迟加载属性(Swift)

转载 作者:IT王子 更新时间:2023-10-29 05:48:46 25 4
gpt4 key购买 nike

我知道 swift 不允许在扩展中声明存储的属性。同样的道理,延迟加载的属性也是被禁止的。我知道计算属性是一种替代方法,但我的任务应该只执行一次。

是否有任何 hack/alternative/overlooked 方法来模仿扩展中的惰性 var?

谢谢!

最佳答案

如果您不需要引用self,您可以使用static var:

extension String {
static var count = 0
static var laughingOutLoud : String = {
count++

return "LOL: \(count)"
}()
}

String.laughingOutLoud // outputs "LOL: 1"
String.laughingOutLoud // outputs "LOL: 1"
String.laughingOutLoud // outputs "LOL: 1"

(您的实现中不需要 count;那只是为了表明它只执行了一次。)

关于ios - 扩展中的延迟加载属性(Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29203065/

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