2016-05-27 89 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