2014-07-02 39 views
9

我试图创造斯威夫特元组的数组,但有很大的难度:如何创建元组数组?

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

以上会导致编译错误。

为什么这样错了?以下工作正常:

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

[斯威夫特阵元组(HTTP的可能重复。 com/questions/24210692/array-of-swples-in-swift) – Rivera

回答

19

它与一个类型别名:

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)] 

更新:作为Xcode的6β3的,阵列语法已更改:

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

这已经改变了Swift - Beta 3. – vacawama

+0

@vacawama:你是对的(但旧的语法仍然有效,只是导致编译器警告)。我已经相应地更新了答案。感谢您的反馈。 –

6

你可以这样做,只是你的任务过于复杂:

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

或使空单:

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

你是对的! 'var tupleArray:(num1:Int,num2:Int)[] = []'只是起作用。 –

+0

是的,元组和数组非常古怪。这个Q&A有更多的奇怪:http://stackoverflow.com/questions/24210692/array-of-tuples-in-swift –

+0

这已经改变了迅速 - Beta 3. – vacawama

2

这也适用:如果你想

fun.append(5,6) 

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

奇怪的是,虽然,append希望只是一组括号中tuple零件标签:

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

这是一个Swift中的元组数组。更多在这里:http://stackoverflow.com/questions/24210692/array-of-tuples-in-swift –

0

不知道有关早期版本的雨燕,但是当你想要提供的初始值这部作品在斯威夫特3://计算器:

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 
}()