mfaani
mfaani

Reputation: 36297

Is there any way to append an element/value to a tuple?

Is there anyway to add a new element to a tuple?

var tuple = (v1: 1,v2: 2)

tuple.v3 = 3 // Error

"error: value of tuple type '(v1: Int, v2: Int)' has no member 'v3'"

Upvotes: 1

Views: 3161

Answers (4)

ScottyBlades
ScottyBlades

Reputation: 14033

While there is no extensible way to convert your array to a tuple as stated above, if you arrived at this question because you are making reusable components, and you like the convenience that variadic declarations can provide, you can move your method body into one that takes an array and let your variadic declaration be an alternate wrapper for the same method.

This

func buttonModels(_ buttonModels: ButtonModel...) {
    self.buttonModels = buttonModels
}

Becomes:

func buttonModels(_ buttonModels: ButtonModel...) {
    self.buttonModels(buttonModels)
}

func buttonModels(_ buttonModels: [ButtonModel]) {
    self.buttonModels = buttonModels
}

Upvotes: 0

Alex Eggers
Alex Eggers

Reputation: 378

It seems to me that you are looking to use a dictionary, not a tuple. See the docs: Tuple

EDIT: As pointed out, tuples can indeed be mutable if you declare them as a var and can be used to hold editable data. My bad!

Upvotes: -4

Alexander
Alexander

Reputation: 63271

If you just need to support some small number of operations, then you can write a function for it.

For example, extending a 2D vector into 3D:

func expand(_ v: (x: Int, y: Int), z: Int) -> (x: Int, y: Int, z: Int) {
    return (x: v.x, y: v.y, z: z)
}

Upvotes: 3

David Pasztor
David Pasztor

Reputation: 54735

No. Each tuple with a different number of elements or a different type of elements represents a different type in the Swift type system. Hence, once you create a tuple, you cannot append elements to it, because that would change the type of the tuple.

Some really basic examples of tuples and their types:

let tupleWithTwoInts = (1,2) //has type (Int,Int)
let tupleWithThreeInts = (1,2,3) //has type (Int,Int,Int)
let tupleWithTwoStrings = ("a","b") //has type (String,String)
let tupleWithIntAndString = (1,"a") //has type (Int,String)
let tupleWithStringAndInt = ("a",1) //has type (String,Int)

Even the order of the elements make a difference in the type of a tuple.

type(of: tupleWithIntAndString) == type(of: tupleWithStringAndInt) //false

Upvotes: 7

Related Questions