2017-01-17 12 views
0

静的変数は常に同じ値を与えます。関数が常に呼び出されないのはなぜですか?静的変数と関数の問題

class SessionManager { 
    static func AddSession(key : String, value : Any) { 
     let session = UserDefaults.standard 
     if session.object(forKey: key) != nil { 
      session.removeObject(forKey: key) 
     } 
     session.setValue(NSKeyedArchiver.archivedData(withRootObject: value), forKey: key)   

    } 

    static func GetSessionValue(key : String) -> Any? { 
     let session = UserDefaults.standard 
     return NSKeyedUnarchiver.unarchiveObject(with: session.value(forKey: key) as! Data) 
    } 

    static var CurrentEmployee : Employee? = SessionManager.GetSessionValue(key: CL.SESSION__CURRENT_EMPLOYEE) as? Employee 

} 

SessionManager.CurrentEmployeeは常に同じです。

答えて

2
static var CurrentEmployee : Employee? = SessionManager.GetSessionValue(...) as? Employee 

が評価される初期値格納さ(タイプ)プロパティである 正確一度、プロパティが最初にアクセスされる

static var CurrentEmployee : Employee? { return SessionManager.GetSessionValue(...) as? Employee } 

自己完結型の例:

class Foo { 

    static var currentNumber = 0 

    static func nextNumber() -> Int { 
     currentNumber += 1 
     return currentNumber 
    } 

    static var storedProp = nextNumber() 

    static var computedProp: Int { return nextNumber() } 
} 

print(Foo.storedProp) // 1 
print(Foo.storedProp) // 1 
print(Foo.storedProp) // 1 

print(Foo.computedProp) // 2 
print(Foo.computedProp) // 3 
print(Foo.computedProp) // 4 

print(Foo.storedProp) // 1 

何が欲しいのは計算プロパティは、各アクセスで評価されるゲッター で、あります

関連する問題