-2

I have these arrays:

var inactiveLocationArray = [String]()
var activeLocationArray = [String]()

I would like to add them to an array like this:

let locationArrays: [[String]] = [self.inactiveLocationArray,self.activeLocationArray]

but it gives error: Value of type (NSObject) -> () -> Controller has no member activeLocationArray

this actually works:

let locationArrays: [[String]] = [["test", "testas"]]
goran
  • 153
  • 2
  • 12
  • 4
    What does "it doesn't work" mean? – matt Feb 17 '17 at 16:33
  • 1
    Possible duplicate of [How to initialize properties that depend on each other](http://stackoverflow.com/q/25854300/2976878) – Hamish Feb 17 '17 at 16:39
  • 1
    You need to set the value of `locationArrays` after your VC has been loaded. When you declare it say `var locationArrays: [[String]]!`, then in `viewDidLoad` you can say `self.locationArrays = [inactiveLocationArray, activeLocationArray]` – Pierce Feb 17 '17 at 16:45
  • @Pierce Or he could just make it `lazy`. – Hamish Feb 17 '17 at 16:45
  • @Hamish - yeah that should work too, although I know in my experience I still have problems with the complier complaining. – Pierce Feb 17 '17 at 16:46
  • thanks you pierce, thats perfect – goran Feb 17 '17 at 16:56

1 Answers1

1

Your code both compiles and works perfectly:

var inactiveLocationArray = [String]()
var activeLocationArray = [String]()
let locationArrays: [[String]] = [inactiveLocationArray,activeLocationArray]

Perhaps it doesn't do what you expect or desire, but it does work. The result is an array of arrays, precisely as expected.

but it gives error: Value of type (NSObject) -> () -> Controller has no member activeLocationArray

That's because your code is in the wrong place. All executable code must be inside a function of some kind. Yours isn't. Example:

class Controller : NSObject {
    func someMethod() {
        var inactiveLocationArray = [String]()
        var activeLocationArray = [String]()
        let locationArrays: [[String]] = [inactiveLocationArray,activeLocationArray]
    }
}

If you move the let locationArrays line out of its containing method (here, someMethod), sure, it won't compile. But that has nothing to do with arrays. It has to do with the fact that the line is executable code, and cannot live off in the ether.

matt
  • 515,959
  • 87
  • 875
  • 1,141