Sunil Karkera
Sunil Karkera

Reputation: 376

Accessing values in Swift 1.2 multi-dimensional arrays

Apologies in advance. I am a newbie learning Swift and have some working experience with C and Ruby. I'm venturing into Swift.

I'm trying to create and access a multi-dimensional array as follows:

var arrayTest: [[(Int, Int, Int, String)]] = []
arrayTest.append([(1, 2, 3, "Test")])
arrayTest.append([(4, 5, 6, "Test1")])

This seems to work fine in Playground. But trying to access as follows does not work:

println(arrayTest[0][0])

I looked at several entries and the Apple Swift docs. But I was still unable to figure this out.

Any insights appreciated. Thank you.

Upvotes: 0

Views: 407

Answers (1)

Ken Garber
Ken Garber

Reputation: 51

Looks like you're trying to make an array of tuples but have an extra set of brackets, meaning you're making an array of arrays of tuples. Also, you append a tuple without putting it in parenthesis. Try:

var arrayTest: [(Int, Int, Int, String)] = []
arrayTest.append(1, 2, 3, "Test")
arrayTest.append(4, 5, 6, "Test1")

You would access an element a little differently. Square brackets return the tuple in arrayTest, and the period returns an element of the tuple.

println(arrayTest[0].0)

This would return 1 (the 0th element of the 0th tuple).

Upvotes: 1

Related Questions