为了演示这个问题,我做了一个香草Cocoa项目。这里是AppDelegate.swift
: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
,它肯定会始终存在。
任何想法如何使用弱懒惰变量?
太棒了!这正是我所期待的。但我开始考虑如果我是过度工程。一个保留不会伤害,对吧?这里唯一的好处是可以防止未来可能的参考周期。 – LShi