为了演示这个问题,我做了一个普通的 Cocoa 项目。这是 AppDelegate.swift
:
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
weak lazy var isGood : NSNumber? = {
return true
}()
func doSomething() {
let result = isGood!
}
func applicationDidFinishLaunching(aNotification: NSNotification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
}
Xcode 给出了这个:
unkown :0: error: cannot convert return expression of type 'NSNumber?' (aka 'Optional') to return type 'NSNumber?'
unkown :0: cannot assign value of type 'NSNumber?' to type 'NSNumber??'
unkown :0: cannot assign value of type 'NSNumber?' to type 'NSNumber??'
在我的实际项目中,它是 MyCustomClass
的另一个对象(而不是 NSNumber)。除了类型是 MyCustomClass
之外,错误是相同的。
如果我从声明中删除 weak
或 lazy
,一切都很好。但我想避免引用计数为 +1,因为 MyCustomClass
是一个 NSViewController
,它肯定会一直存在。
知道如何使用弱惰性变量吗?
最佳答案
软弱和懒惰混在一起不好。错误消息对于解释正在发生的事情完全没有用,但本质上 lazy
和 weak
是相互矛盾的:
lazy
告诉 Swift,您不想在第一次访问变量之前创建它,但是一旦创建了它,您希望无限期地保留它以供将来引用,而weak
告诉 Swift 你不希望你的变量成为阻止你的变量被释放的最后一个链接,这违背了lazy的“无限期保持”目标
变量。
你可以通过模拟 lazy
来解决这个问题,就像这样:
class Foo {
weak var isGoodCache : NSNumber?
private var makeIsGood : NSNumber {
isGoodCache = true
return isGoodCache!
}
var isGood:NSNumber? {
return isGoodCache ?? makeIsGood
}
}
关于Swift 弱惰性变量不会编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38171933/