2016-05-27 91 views
0

在這種情況下,靜態變量textView包含在Holder結構中。
但我遇到了一個問題,每次用戶調用此函數時都必須設置「Holder.textView.fieldEditor = true」。
我該如何讓這個動作只運行一次?如何在函數中設置靜態變量的屬性

func myTextView() -> NSTextView { 

    struct Holder { 
     static var textView = NSTextView() 
    } 

    Holder.textView.fieldEditor = true 
    return Holder.textView 
} 

回答

0

struct Holder { 
    static var textView = NSTextView() 
} 

應該將函數的範圍之外定義。否則,每次調用myTextView()時,都會定義一個新的Holder結構並進行實例化。

這使得static var無用於您的目的。

另一方面,如果在函數的外部定義了Holder,則該值在多次調用之間保持不變。

enter image description here