How To Change Tuple Fields Names

The tuple is an amazing thing in Swift that allows you to create some kind of new data structure that you don’t need to declare before. It’s just like an array with different types. By default, its fields are the next number but there is an option to change those names.

Let’s create a simple tuple with Int and String and put it into the function getTuple. You can create different types as well.

func getTuple() -> (Int, String) {
    
var result = (0, “”)
    
return result
}

If you want to change that string to something else you need to use .1 to do it.

result.1 = “Hi”

However, there is an option to change these names.

Just put names before values.

var result = (time: 0, text: “”)
result.
text = “Hi”

The previous .1 also works.

It works well locally but if you get this tuple inside another function then you still need use .0, .1, and so on.

func someFunction() {
    
var tuple = getTuple()
    tuple.
text = “Hello”
}

It just doesn’t work.

To solve it you need to name it in the function signature.

func getTuple() -> (time: Int, text: String) {

Now, this code works.

func someFunction() {
    
var tuple = getTuple()
    tuple.
text = “Hello”
}