fuzzygoat
fuzzygoat

Reputation: 26223

Swift 1.2 Array declaration, extra brackets?

Using Swift 1.2 is there a difference between [String] and [(String)] when declaring an array, or are they just the same?

var testArray_001: [String] = []      // Declaration = [String]
var testArray_002: [String] = Array() // Declaration = [String]
var testArray_003 = [String]()        // Declaration = [(String)]

Upvotes: 2

Views: 679

Answers (1)

Antonio
Antonio

Reputation: 72760

There is no difference. The (String) form actually means a tuple with one value of String type, but it's equivalent to just saying a String.

For instance, consider the following array:

var array = [String]()

you can append a string element as usual:

array.append("raw string")

but you can also add a tuple containing one string value:

let tuple = (namedValue: "from tuple")
array.append(tuple)

Note that the equivalence doesn't stop here. If you have a function/method accepting n parameters:

func aFunc(#param1: Int, #param2: String, #param3: Double) {}

when invoking it you can provide the list of parameters:

aFunc(param1: 1, param2: "text", param3: 3.14)

but you can also group the parameters into a tuple, and just it to the function

let params = (param1: 1, param2: "text", param3: 3.14)
aFunc(params)

Upvotes: 2

Related Questions