Clarity in Swift code
var numbers = [-1, 0, -9, -3, 1, 3, 4]
let first = numbers.first!
let (min, max) = numbers.map({($0,$0)}).reduce((first,first), combine: {($0.0 < $1.0 ? $0.0 : $1.0, $0.0 > $1.0 ? $0.0 : $1.0)})
As you can probably guess, this Swift snippet compiles and works, it finds the minimum and the maximum values inside the numbers
array.
This code represents my biggest fear regarding Swift. I’m sure many people will actually enjoy this, most won’t care enough to think about it now, but I think this type of code is exactly what makes great languages hard for beginners to grasp.
First, is this is real production code? After all I choose this snippet to make a point. If it compiles someone will ship it, commit it and even share it. Of this I have no doubt.
I come up with this gibberish by “cleaning” up code:
var numbers = [-1, 0, -9, -3, 1, 3, 4]
let first = numbers.first!
var min = first
var max = first
for i in numbers {
if i < min {
min = i
}
if i > max {
max = i
}
}
There’s nothing wrong with this code, it’s easy to understand, and it finds out the minimum and maximum while iterating the array only once. But I wanted it shorter, and with constants instead of variables.
let min = numbers.reduce(first, combine: { $0 < $1 ? $0 : $1 })
let max = numbers.reduce(first, combine: { $0 > $1 ? $0 : $1 })
A bit weirder if you are not used to the Shorthand Argument Names but still readable. It now takes two iterations to find the values, but I’m more interested in clarity and conciseness.
let (min, max) = numbers.map({($0,$0)}).reduce((first,first), combine: {($0.0 < $1.0 ? $0.0 : $1.0, $0.0 > $1.0 ? $0.0 : $1.0)})
This is where it gets ugly. I’m now using map
to create a list of tuples, then reduce
folds that into a tuple with the minimum and maximum. It won’t win a IOCCC, but it’s not pretty.
Please don’t commit code like this. If you looked at those samples and thought: “this is so stupid, why is he doing this?”; you’re on the right side.
Shorter code isn’t necessarily faster. You are not charged by the character. And if you, like me, are still on the fence between Objective-C and Swift, please prefer clear vs. short code despite what the language enables.