How do I add a tuple to a Swift Array?
Since this is still the top answer on google for adding tuples to an array, its worth noting that things have changed slightly in the latest release. namely:
when declaring/instantiating arrays; the type is now nested within the braces:
var stuff:[(name: String, value: Int)] = []
the compound assignment operator, +=
, is now used for concatenating arrays; if adding a single item, it needs to be nested in an array:
stuff += [(name: "test 1", value: 1)]
it also worth noting that when using append()
on an array containing named tuples, you can provide each property of the tuple you're adding as an argument to append()
:
stuff.append((name: "test 2", value: 2))
You have two issues. First problem, you're not creating an "array of tuples", you're creating an "optional array of tuples". To fix that, change this line:
var myStringArray: (String,Int)[]? = nil
to:
var myStringArray: (String,Int)[]
Second, you're creating a variable, but not giving it a value. You have to create a new array and assign it to the variable. To fix that, add this line after the first one:
myStringArray = []
...or you can just change the first line to this:
var myStringArray: (String,Int)[] = []
After that, this line works fine and you don't have to worry about overloading operators or other craziness. You're done!
myStringArray += ("One", 1)
Here's the complete solution. A whopping two lines and one wasn't even changed:
var myStringArray: (String,Int)[] = []
myStringArray += ("One", 1)