Friday, February 15, 2019

Using Tuples As Lightweight Types in Swift

John Sundell:

Even though a tuple can have labels, you are always free to ignore those when creating an instance. This can help make call sites look really nice and clean, for example when dealing with vector types, like coordinates.

[…]

Tuples can also be super useful when checking if multiple values are equal. Even though they don’t conform to the Equatable protocol (or any protocol for that matter), the Swift standard library defines == overloads for tuples that contain values that themselves are equatable.

[…]

It turns out that the argument list of any closure can in fact be described using a tuple, and since - thanks to first class functions - all functions are also closures, we can actually use a tuple to pass arguments to a function. All we have to do is to make Swift treat a function as a closure. To do that we could define a call function that takes any function and applies its required arguments to it[…]

John Sundell:

Tuples can not only be super useful in order to group multiple related local variables into one, but can also be a great way to combine throwing expressions

Comments RSS · Twitter

Leave a Comment