5

I can easily write a multi-dimensional array in Swift when all the dimensions are of the same type, for example:

var totalTime : [[Int]]

How would I get the first dimension to be String and the second dimension Int?

4
  • That doesn't make sense: a multi-dimensional array is an array of arrays, so an Integer array would be an array of Integer arrays. What do you mean by "second dimension?" Commented Sep 21, 2014 at 1:56
  • I can accomplish what I need with two arrays, but I am curios as to whether there is a capability to do it in one multi-dimensional array. I want one dimension to store String values and one to store Int values. So for example, totalTime[0] would return "AstroCB" and totalTime[0][0] would retrieve 555. Just trying to see what is possible. Commented Sep 21, 2014 at 2:01
  • Ah, I see. You'd probably be better off going with erdekhayser's solution below. Commented Sep 21, 2014 at 2:02
  • I think you can find better solution here Commented Feb 9, 2018 at 13:49

1 Answer 1

11

I would recommend using an array of tuples instead. What you want could be accomplished using an array of type Any, but it is not a good idea.

Instead, your array should be [[(String, Int)]]. This would also be more compact than what you want to do.

var myArray: [[(String, Int)]] = []
Sign up to request clarification or add additional context in comments.

4 Comments

This causes a compile error I tried var arrayTest : [[(String, Int)]]
@user3412502 Not sure why. This code works fine in my playground: var arrayTest: [[(String, Int)]] = []; arrayTest.append([("Hello", 2)]); println(arrayTest);
Thanks, I was missing the = []. This answers my questions! Thank you!
@erdekhayser, thanks. How can we modify values of these tuples? A simple tuple like myTuple = (123, "hello") can be modified like myTuple.1 = "changed". But myArrayOfTuples.append([(123,"how","to","modify")]) cannot be changed by myArrayOfTuples[0].1 = "no way", or myArrayOfTuples[0](1) = "no way", or myArrayOfTuples[0][1] = "no way". Thanks

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.