5

I am trying to make an array of arrays where each nested array has a string and an integer.

I have seen you can use structs but all I want to do is make them a constant, and I want to know if there is a way to do it without having to type loads of extra stuff

let items: [[String, Int]] = [["A", 1], ["B", 2], ["C", 3]]
2
  • 1. Those aren't tuples. Why is this tagged with tuples? 2. What extra stuff are you referring to? Your question is not clear at all. Commented Jan 12, 2018 at 18:43
  • How is it not clear? I want to mix strings and ints in an array. Commented Jan 12, 2018 at 18:52

3 Answers 3

7

I think what you want is an array of tuples, not an array of arrays. That implementation would look like this:

let items: [(String, Int)] = [("A", 1), ("B", 2), ("C", 3)]

You could access these properties like this:

let itemOneString = items[0].0 // "A"
let itemOneInt = items[0].1 // 1
Sign up to request clarification or add additional context in comments.

Comments

1

It will work for you:

let items: [[(String, Int)]] = [[("A", 1)], [("B", 2)], [("C", 3)]]

3 Comments

Why the extra layer of array? Why not simply have an array of tuples instead of an array of arrays of tuple?
@rmaddy why not to have struct instead of tuple? It's way more representative rather then just a tuple
Ask the OP, not me. I agree a struct is better. But that has nothing to do with your answer which has a needless extra layer of arrays.
1
  1. Array is collection of similar data types. It can not contain heterogeneous types data.

But if you still want to do it. There are other workarounds like create array of dictionary like this.

let items: [[String: Any]] = [["String" : "A", "Int" : 1], ["String" : "B", "Int" : 2]]

or create an array of Tuples.

let items: [(String, Int)] = [("A", 1), ("B", 2), ("C", 3)]

You can add any number of items in Tuple or Dictionary.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.