tera
1
Got this rough idea of allowing default values in tuples:
typealias T = (Int, Double, String = "")
T(1, 2) // ✅
func foo(_ v: (Int, Double, String = "")) {}
foo((1, 2)) // ✅
typealias R = (x: Int, y: Double = 2, z: String)
R(x: 1, z: "3") // ✅
func foo(_ v: (x: Int, y: Double = 2, z: String)) {}
foo((x: 1, z: "3")) // ✅
Worth having this in Swift?
1 Like
allevato
(Tony Allevato)
2
My general thinking around tuples is that when you start doing things like assigning names to them (typealias T = ...) or trying to reach for other behavior to add to them, it's really just time to make it a dedicated struct.
15 Likes
tera
3
The tuple may be provided by the API and the API author may not need to give it a typealias name or an added functionality. OTOH the user of this API may have such a need, and he or she can't change the tuple to a struct.
Fun fact: default arguments used to be part of the tuple's type in the Swift 2 days, when functions would semantically always have a single input value, which could be a tuple. This caused no end of trouble!
However, you can probably do what you want with a macro. Have the expansion emit a function that takes the parameters with defaults and forms a tuple value from those arguments. Or even just write that function by hand.
6 Likes