Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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[]()
like image 499
Doug Smith Avatar asked Jul 02 '14 19:07

Doug Smith


2 Answers

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
like image 82
Nate Cook Avatar answered Nov 16 '22 03:11

Nate Cook


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
}()
like image 26
MH175 Avatar answered Nov 16 '22 02:11

MH175