この問題を示すために、私はバニラのCocoaプロジェクトを作成しました。ここでAppDelegate.swift
です:Xcodeのは、この与え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
}
}
:私の実際のプロジェクトで
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??'
を、それが(代わりのNSNumberの)MyCustomClass
の別のオブジェクトです。エラーは、タイプがMyCustomClass
以外は同じです。
宣言からweak
またはlazy
を削除しても問題ありません。しかし、MyCustomClass
は常にNSViewController
であるため、参照カウントが+1にならないように保存したかったのです。
弱い怠惰な変数をどのように使用するか考えてみましょうか? Dが初期化されなければならない場合
素晴らしい!これはまさに私が探していたものです。しかし、もし私が過剰工学であると思ったのです。 1つの保持は傷ついていませんよね?ここでの唯一の利点は、将来可能な参照サイクルを防ぐことができることです。 – LShi