I tried to use pattern matching. I have code like this:
struct Quantity {
let quantity: Int
let unit: Unit?
init(_ quantity: Int, unit: Unit? = nil) {
self.quantity = quantity
self.unit = unit
}
}
enum Unit {
case liter
case kilogram
case meter
}
and I wanted to write a function that formats such a quantity nicely. I started writing it like this:
You can do it with ~=. Search for something like "Swift pattern matching ~=".
But, it doesn't make sense for Quantity. The reason you switch on an enum is to access its associated values and/or handle multiple cases. The only thing you need to switch on here is unit.
There’s nothing built in for it, because there’s no way to “reverse” a struct initializer. But you can always have a computed property return a tuple:
This is a cool trick, but practically when is this better than switch (q.quantity, q.unit) {? You have to write out the property names in full in both cases, and obviously the pack approach has a lot more associated boilerplate (and even the call site is longer character-count wise).
and even the call site is longer character-count wise
Sure, if your variable name is q. With a realistic variable name, like latestQuantity, the difference starts to start.
However, I tend to agree with your larger point. I doubt I’ll adopt this technique in my own code. I was mostly just using this as an excuse to work on my variadic generic skills (-: