Xavier Garcia Rubio
Xavier Garcia Rubio

Reputation: 105

Storing and getting data form a Array of Arrays in Swift

I'm working on Swift and I've some problems on multidimensional arrays. In playground, I test this code:

//some class
class Something {
    var name:String = ""
}

//i create an array (will store arrays)
var array = [NSArray]()

//create some Something objects
var oneSomething:Something = Something()
var twoSomething:Something = Something()

//fill Something names for sample
oneSomething.name = "N1"
twoSomething.name = "N2"

//create an array of Something's
var array2 = [Something]()

//append the two objets to array2
array2.append(oneSomething)
array2.append(twoSomething)

//append array2 to array N times just for testing
array.append(array2)
array.append(array2)

//on playground I test what I'm storing:
array[0]
array[0][0]
array[0][0].name

And this is the result I'm getting on the last 3 lines:

enter image description here

So, in the first line I access first level of arrays correctly, in the second line I access second line correctly two... but... in the third line I get 'nil' instead name of the Something object. What I'm doing wrong, how can I store and get multidimensional arrays in this example.

Thanks.

Upvotes: 2

Views: 4240

Answers (2)

jfgrang
jfgrang

Reputation: 1178

The problem is that you are putting an object Something inside the array.

You need to unwrap it as the object type

if let object = array[0][0] as? Something {
    object.name
}

or you need to define the array as an array containing Something object

//i create an array (will store arrays)
var array = [Array<Something>]()
...
array[0][0].name

Regards

Upvotes: 2

Bartłomiej Semańczyk
Bartłomiej Semańczyk

Reputation: 61774

Because you declared:

var array = [NSArray]()

instead of:

var array = [[Something]]()

NSArray comes from Objective-C and it is not clear for Swift what is inside, so compiler doesn't know what type of objects that array contains.

However if you want to leave var array = [NSArray]() you must cast it:

(array[0][0] as Something).name

to tell the compiler that this is Something type. Then compiler knows about properties of that object. Otherwise this is AnyObject and its properties are unknown.

Upvotes: 2

Related Questions