Access a static variable from a non-static method in Swift

I know that you cannot access a non-stationary class variable from a static context, but what about a different path? 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 an error message MyClass does not have a member named myArr. I thought that static variables were visible to both static and non-stationary methods, so I don’t know where I am going wrong.

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

+4
source share
4 answers

You need to specify the class name before the variable.

class MyClass {

    static var myArr = [String]()

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

You just need to add the class name.

class MyClass {

    static var myArr = [String]()

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

}

You can access the array in two different ways:

MyClass().getArr()

or

MyClass.myArr
+2

self.dynamicType:

class MyClass {

    static var myArr = [String]()

    func getArr() -> [String] {
        return self.dynamicType.myArr
    }
}
+2
source

In Swift3, the dynamic type is deprecated. You can use type (from :)

struct SomeData {
  static let name = "TEST"
}

let data = SomeData()
let name = type(of:data).name
// it will print TEST
+2
source

All Articles