Author Topic: How do I add a tuple to an array in Swift?  (Read 5165 times)

kjmcneish

  • Administrator
  • *****
  • Posts: 719
    • View Profile
How do I add a tuple to an array in Swift?
« on: May 19, 2015, 11:15:45 AM »
There are a few ways to add a tuple to an array of tuples. For example, Here is a tuple array declaration:

Code: [Select]
var results = Array<(code: Int, message: String)>()
It declares an array of named tuples that have Int (code) and String (message) values.

You can use the compound assignment operator to append a tuple to the array. Notice how the tuple is nested within square brackets :

Code: [Select]
results += [(code: 1, message: "Invalid Date")]
You can also use the Array's append method, which doesn't require the square brackets:

Code: [Select]
results.append(code: 1, message: "Invalid Date")
All the best!
Kevin McNeish
Author of Learn to Code in Swift: https://itunes.apple.com/us/book/learn-to-code-in-swift/id942956811?mt=11