Always write a generalized version of your algorithm
Suppose you want to find the minimum value in an array. Well, the Swift standard library has you covered:
Ok that’s cool. But suppose you have an array of strings of integers and you want the minimum numeric value.
Well, I guess you could map them to Int
and then use the same function:
Nope, compiler error. String.toInt
returns an Int?
, because maybe the string isn’t a number.
Fair enough. I happen to know with my intimate knowledge of the problem domain that we can just ignore non-numeric values. So maybe filter those out?
Nope, more compiler errors, because now we have only non-nil
values, but they’re still optionals and an Int?
doesn’t conform to Comparable
. So maybe another map
to force-unwrap the results (force unwrap is OK because the filter will guarantee no non-nil elements):1
Ok that compiles now and does return the minimum numeric…
View original post 457 more words
Posted on July 16, 2014, in Programming. Bookmark the permalink. Leave a comment.
Leave a comment
Comments 0