0

The project needs a big Dictionary, so I place it in anohher swift file that makes the codes look clean. But I got a "Expected declaration" error.

class AA{

    var a:Dictionary<String,Array<String>> = [:]
    a["a"] = ["aa", "aaa"] // error: Expected declaration
    ...
    ...

}

and I want to get it like this:

let aa = AA.a

By now, I have to add it in a func to get it.

class AA{

    func getVar()->Dictionary<String,Array<String>>{

        var a:Dictionary<String,Array<String>> = [:]
        a["a"] = ["aa", "aaa"]
        a["b"] = ["bb", "bbb"]

        return a
    }

}

Any simple way to solve this?

@dasblinkenlight your suggestion is get variable from another viewController, it's a little difference from mine.

jdleung
  • 1,088
  • 2
  • 10
  • 26
  • `Expected declaration` means the code **must** run within a function / method. You cannot run code on the top level of the class. And `AA.a` won't work anyway because it's not a type property. – vadian Feb 25 '17 at 10:02
  • Possible duplicate of [swift accessing variable from another file](http://stackoverflow.com/questions/28002847/swift-accessing-variable-from-another-file) – Mitesh jadav Feb 25 '17 at 10:07
  • Unrelated, by why don't you clean this up with a Dictionary literal? http://pastebin.com/cVcThQ3p – Alexander Feb 25 '17 at 10:11
  • @Alexander This is not unrelated at all - that's exactly his problem. – Sergey Kalinichenko Feb 25 '17 at 10:12
  • @dasblinkenlight Oh I just saw the first code snippet. Kinda glanced over the question :p – Alexander Feb 25 '17 at 10:13

2 Answers2

2

The problem is not that you have a dictionary in another file, but that you have assignments outside of a method.

Replacing assignments with a declaration will fix this problem:

class AA {
    static let a = [
        "a" : ["aa", "aaa"]
    ,   "b" : ["bb", "bbb", "bbbb"]
    ,   "c" : ["cc"]
    ]
}

Now you can use AA.a in other classes.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

As per my understanding , You can't access local variables from another class, You can access it in only of that class method only.

Accessing var from another class,

var someVariable: Type = xValue

Now create object of that class where you have declared variable & access it like,

var getThatValue = yourViewControllerObject.someVariable

Access var with in the same class,

 self.yourVar

Or,

static let yourProperty = 0


ClassName.yourProperty  //  & for swift 3 it would be type(of: self).yourProperty

This interesting topic is discussed nicely in the following links,

Access variable in different class - Swift

Access static variables within class in Swift

In your case i think you have to declare var as a static out of method scope

Community
  • 1
  • 1