Destructuring tuples is a very common way to improve the use of Tuples. It does not work with computed properties.
Take this code for example:
var hourMinute: (Int, Int) {
let date = Date()
let cal = Calendar.current
let hour = cal.component(.hour, from: date)
let minute = cal.component(.minute, from: date)
return (hour, minute)
}
print(hourMinute.0)
First of all I had to name this tuple hourMinute
which is honestly not the greatest name. Then I had to access the value by using the index of the item in the tuple. I can infer from the name hourMinute
that hour is 0, and minute 1.
Of course I can improve the ambiguity by labeling:
var hourMinute: (hour: Int, minute: Int)
print(hourMinute.hour)
However destructuring is a really great feature that allows you to pull the tuple apart into multiple variables all within a single assignment.
let (hour, minute) = hourMinute
print(hour)
The problem here is that I needed to create a local destructured version to my computed property: hourMinute
So naturally, I'd like to destructure the computed property. This works out really nicely. I don't need to make a hodgepodge name hourMinute
Instead I could define it a destructured tuple right from the get go.
var (hour, minute): (Int, Int) {
let date = Date()
let cal = Calendar.current
let hour = cal.component(.hour, from: date)
let minute = cal.component(.minute, from: date)
return (hour, minute)
}
This does not work. The compiler throws Getter/setter can only be defined for a single variable
In my opinion this is not ideal because you'd expect it work. But it does not.
Learners of Swift are going to pickup destructuring perhaps from a tutorial and then attempt something like this and become confused. "Oh I guess that doesn't work."