Access static variable from non static method in S

2019-05-02 21:53发布

I know that you cannot access a non static class variable from within a static context, but what about the other way around? I have the following code:

class MyClass {

    static var myArr = [String]()

    func getArr() -> [String] {
        return myArr
    }

However, when I try to compile this, I get the error MyClass does not have a member named myArr. I thought static variables were visible to both static and non static methods, so I don't know where I am going wrong.

I am on a Macbook running OS X Yosemite using Xcode 6.3.

4条回答
爷的心禁止访问
2楼-- · 2019-05-02 22:14

You just need to add the class name.

class MyClass {

    static var myArr = [String]()

    func getArr() -> [String] {
        return MyClass.myArr
    }

}

You could access you Array from two different ways:

MyClass().getArr()

or

MyClass.myArr
查看更多
来,给爷笑一个
3楼-- · 2019-05-02 22:28

In Swift3, dynamicType is deprecated. You can use type(of: )

struct SomeData {
  static let name = "TEST"
}

let data = SomeData()
let name = type(of:data).name
// it will print TEST
查看更多
贼婆χ
4楼-- · 2019-05-02 22:30

You need to include the class name before the variable.

class MyClass {

    static var myArr = [String]()

    func getArr() -> [String] {
        return MyClass.myArr
    }
}
查看更多
你好瞎i
5楼-- · 2019-05-02 22:30

You can also use self.dynamicType:

class MyClass {

    static var myArr = [String]()

    func getArr() -> [String] {
        return self.dynamicType.myArr
    }
}
查看更多
登录 后发表回答