爲了演示這個問題,我做了一個香草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