iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
😳

[Swift] Tuples can be initialized element-wise

に公開

I was quite surprised to find that Swift's Tuples can apparently be initialized element by element.

let tuple: (Int, String, Bool)
tuple.0 = 42
print(tuple)     // Still an error here
print(tuple.0)   // This does not result in an error
if Bool.random() {
    tuple.1 = "Hello"
} else {
    tuple.1 = "Goodbye"
}
tuple.2 = true
print(tuple)     // This works here

It seems the behavior is the same as writing it like this.

let tuple.0: Int
let tuple.1: String
let tuple.2: Bool

I have often used this with single constants, but I didn't think the same could be done with Tuples.

let x: Int
if Bool.random() { 
    x = 42
} else {
    x = 46
}

I can't quite think of a specific use case, but it's good to keep in mind so it doesn't catch you off guard.

Discussion