5

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.

2
  • 2
    I don't know the exact syntax for swift, but try something like return MyClass.myArr Commented Jul 1, 2015 at 17:39
  • @SvetlanaSlutstokyovich: Make that an answer to earn some swift(!) points – oops, too late :( Commented Jul 1, 2015 at 17:43

4 Answers 4

6

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
Sign up to request clarification or add additional context in comments.

Comments

5

You need to include the class name before the variable.

class MyClass {

    static var myArr = [String]()

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

1 Comment

This will be a problem when myArr gets overwritten in a MyChildClass, getArr() will return value defined in MyClass, not in MyChildClass.
2

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

2 Comments

Is using self.myArr an acceptable way to do this as well?
Just from a class method and you don't need self explicitly
2

You can also use self.dynamicType:

class MyClass {

    static var myArr = [String]()

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.