请使用以下代码:
var tupleArray: [(firstName: String, middleName: String?)] = []
tupleArray.append(firstName: "Bob", middleName: nil)
tupleArray.append(firstName: "Tom", middleName: "Smith") // causes an error
我想要一个由名字和中间名组成的元组数组,中间名可以是nil或者有一个值(因此,可选)。但是使用上面的创建代码,第三行给了我一个错误。为什么?我该如何解决这个问题?
答案 0 :(得分:11)
这可能是编译器错误。与How do I create an array of tuples?中一样, 您可以将类型别名定义为变通方法:
typealias NameTuple = (firstName: String, middleName: String?)
var tupleArray: [NameTuple] = []
tupleArray.append( (firstName: "Bob", middleName: nil) )
tupleArray.append( (firstName: "Tom", middleName: "Smith") )
答案 1 :(得分:0)
另一种解决方法是明确制作Optional<String>.Some
。
var tupleArray: [(firstName: String, middleName: String?)] = []
tupleArray.append(firstName: "Bob", middleName: nil)
tupleArray.append(firstName: "Tom", middleName: .Some("Smith"))
答案 2 :(得分:-1)
Something Intresting.It似乎是一些bug,但我们可以使用其他语法添加尝试使用以下方式
var pfc : [(prime: Int, count: Int)] = []
pfc.append(prime: 2, count: 2)
pfc += [(prime: 3, count: 4)]
var p = 5
var c = 1
var tuple = (prime: p, count: c)
pfc += [tuple]
对于optinal变量,请看下面的代码(originally provided by Martin R),它适用于我
typealias tupleArray = (firstName: String, middleName: String?)
var fun1: [tupleArray] = [tupleArray]()
fun1.append((firstName: "Bob", middleName: nil))
fun1.append((firstName: "Tom", middleName: "Smith"))
println(fun1)