How do I create an array of tuples in Swift where one of the elements in the tuple is optional?
Take the following code:
var tupleArray: [(firstName: String, middleName: String?)] = []
tupleArray.append(firstName: "Bob", middleName: nil)
tupleArray.append(firstName: "Tom", middleName: "Smith") // causes an error
I need an array of tuples consisting of a name and a middle name, the middle name can be nil or have a value (thus optional). However, with the above create code, the third line gives me an error. What for? How do I get around this?
+3
source to share
3 answers
This could be a compiler error. How in How do I create an array of tuples? , you can define a type alias as a workaround:
typealias NameTuple = (firstName: String, middleName: String?)
var tupleArray: [NameTuple] = []
tupleArray.append( (firstName: "Bob", middleName: nil) )
tupleArray.append( (firstName: "Tom", middleName: "Smith") )
+11
source to share
Something interesting. This seems to be an error somehow, but we can add using a different syntax using the following method
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]
for optical variables the following code ( originally provided by Martin R ) passes , it works fine for me
typealias tupleArray = (firstName: String, middleName: String?)
var fun1: [tupleArray] = [tupleArray]()
fun1.append((firstName: "Bob", middleName: nil))
fun1.append((firstName: "Tom", middleName: "Smith"))
println(fun1)
-1
source to share