Doug Smith
Doug Smith

Reputation: 29326

How do I create an array of tuples?

I'm trying to create an array of tuples in Swift, but having great difficulty:

var fun: (num1: Int, num2: Int)[] = (num1: Int, num2: Int)[]()

The above causes a compiler error.

Why's that wrong? The following works correctly:

var foo: Int[] = Int[]()

Upvotes: 12

Views: 13961

Answers (6)

SimonL
SimonL

Reputation: 1838

As of Swift 5.7, the following works.

  1. Creating an empty array that you can populate later, using the standard array initialiser with the tuple's type signature.
/* Create empty array of (num1: Int, num2: Int) tuples */
var array1 = [(num1: Int, num2: Int)]()

/* Can be populated with (Int, Int) tuples
   (the labels are optional)... */
for i in 1...8 {
  array1.append((i, i*i))
}

/* ...or (num1: Int, num1: Int) tuples */
for i in 9...12 {
  array1.append((num1: i, num2: i*i))
}
  1. Creating an initialised array using Array(repeating: <value>, count:):
var array2 = Array(repeating: (num1: 0, num2: 0), count: 8)

Upvotes: 0

Azharuddin Khan
Azharuddin Khan

Reputation: 1

It can be done like this as well.

      var arr : [(num1: Int, num2 : Int)] = {
          let arr =  Array(repeating: (num1:  0, num2 :0), count : n)
          return arr
     }()  

Upvotes: -2

MH175
MH175

Reputation: 2334

Not sure about earlier versions of Swift, but this works in Swift 3 when you want to provide initial values:

var values: [(num1: Int, num2: Int)] = {
    var values = [(num1: Int, num2: Int)]()
    for i in 0..<10 {
        values.append((num1: 0, num2: 0))
    }
    return values
}()

Upvotes: 1

Nate Cook
Nate Cook

Reputation: 93296

You can do this, just your assignment is overly complicated:

var tupleArray: [(num1: Int, num2: Int)] = [ (21, 23) ]

or to make an empty one:

var tupleArray: [(num1: Int, num2: Int)] = []
tupleArray += (1, 2)
println(tupleArray[0].num1)    // prints 1

Upvotes: 10

Martin R
Martin R

Reputation: 540105

It works with a type alias:

typealias mytuple = (num1: Int, num2: Int)

var fun: mytuple[] = mytuple[]()
// Or just: var fun = mytuple[]()
fun.append((1,2))
fun.append((3,4))

println(fun)
// [(1, 2), (3, 4)]

Update: As of Xcode 6 Beta 3, the array syntax has changed:

var fun: [mytuple] = [mytuple]()
// Or just: var fun = [mytuple]()

Upvotes: 24

vacawama
vacawama

Reputation: 154721

This also works:

var fun:Array<(Int,Int)> = []
fun += (1,2)
fun += (3,4)

Oddly though, append wants just one set of parens:

fun.append(5,6)

If you want the labels for the tuple parts:

var fun:Array<(num1: Int, num2: Int)> = []
fun += (1,2)                  // This still works
fun.append(3,4)               // This does not work
fun.append(num1: 3, num2: 4)  // but this does work

Upvotes: 3

Related Questions