Tuples - Swift Unwrapped ep. 86
Iâm trying to branch out on resources and took a listen to the âSwift Unwrappedâ podcast episode 86 âTuplesâ, available on most podcast providers and online.
Difficulties using in arrays when want to pass to things conforming to organization protocols
No conformance to codable, equitable, hashable
No elegant solution found yet
Interestingly c++ tuples are equitable but not hashable
Limit of 12 items in a tupleÂ
more than you should ever need
Having non-nominal type with 12 members over named struct? Not preferable
 What is threshold for stopping & creating named type?
4-5, slap a name on that bad boy
Public APIs returning tuplesÂ
Too hard to use generallyÂ
Being unnamed makes them unwieldy to refer to in conversation & documentation
Not suited for public api use, but nice for a structure for a subset of an algorithm
Once you start crossing data boundaries with a tuple it begins to lose its power
Can add labels, but at that point, would a struct be more appropriate?
You Can name the members of a tuple when you create it
Adding labels means autocomplete will only show the labels but you can still refer to them by indexÂ
In swift can have very locally scoped nominal types
Gives a nearly anonymous named struct or class
Itâs rare that a tuple can give you new powers that a strategically placed struct would not
Itâs Easier to add a member to a struct than a tuple
Canât have a tuple with no elements, can have a struct with no members
Need to provide a unique hashable identifier: You can create an instance of hashable empty struct and every other instance of that struct will match, but nothing else will. Gives type safety because thereâs no way even if named same something can give the same identifier.
Performance concerns using struct over tuple?
Minor size diffs of name and debug I do for a struct vs tuple, but thatâs nearly insignificant for most applications
Tuple might not be able to be bit packed the same way as structs for size optimization
Order is important in both structures
Tuples with different labels donât impact equality or hashability
Can compare 2 tuples with same value types but different label names
Issues of not having a type, if using tuples and have a 3D point tuple and an rgb color space tuple swift would let us compare them even though that makes no sense to do
If itâs important to define semantics of a type that matches the type signature of another, name it!
Cannot treat tuples like collections (think array protocols)
C fixed length arrays imported as tuples in swift
But do we want to add more complexity to something that should be rarely used?
For that fixed length case might be better to have concept of dependent types of extending tuples to have more & more power