How do I create an array of tuples?

前端 未结 4 967

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)[]()
相关标签:
4条回答
  • 2020-12-10 13:52

    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]()
    
    0 讨论(0)
  • 2020-12-10 14:04

    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
    }()
    
    0 讨论(0)
  • 2020-12-10 14:07

    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
    
    0 讨论(0)
  • 2020-12-10 14:13

    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
    
    0 讨论(0)
提交回复
热议问题