简体   繁体   English

如何在函数的静态变量中设置属性

[英]How to set property in static variable in function

In this case the static variable textView is contained in Holder struct. 在这种情况下,静态变量textView包含在Holder结构中。
But I encountered a problem that I have to set "Holder.textView.fieldEditor = true" every time when user invoke this function. 但是我遇到一个问题,每次用户调用此函数时,都必须设置“ Holder.textView.fieldEditor = true”。
How do I let this action only run once? 如何让此操作仅运行一次?

func myTextView() -> NSTextView {

    struct Holder {
        static var textView = NSTextView()
    }

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

This 这个

struct Holder {
    static var textView = NSTextView()
}

should be defined outside the scope of your function. 应该在功能范围之外定义。 Otherwise each time you call myTextView() a new Holder struct is defined and instantiated. 否则,每次调用myTextView()都会定义并实例化一个新的Holder结构。

This makes the static var useless for your purpose. 这使static var无法用于您的目的。

On the other hand, if you define Holder outside the function the value does persist among multiple calls. 另一方面,如果您在函数外部定义Holder ,则该值会在多次调用之间保持不变。

Look

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM