As an exercise in learning Swift, I'm trying to create minimum and maximum extension methods on Array
using a shared method called comparest
. Everything is tested and works well, except for one thing: I cannot use the minimum
function without a parameter. I've specified a default parameter value of nil
, but Apple's Swift compiler does not like it when I call minimum
without this parameter.
Here are my method definitions. They compile just fine.
extension Array {
func comparest<C: Comparable>(comparator: T -> C, _ op: (C, C) -> Bool) -> T? {
var min = self.first
for elem in self {
if op(comparator(elem), comparator(min!)) {
min = elem
}
}
return min
}
func minimum<C: Comparable>(var _ comparator: (T -> C)? = nil) -> T? {
if comparator == nil {
comparator = { elem -> C in elem as C }
}
return self.comparest(comparator!, { $0 < $1 })
}
}
(If you're wondering why I say comparest(comparator!, { $0 < $1 })
instead of comparest(comparator!, <)
, see my related question.)
If I say
var array = [3, 4, 1, 9]
var min = array.minimum({ $0 })
everything works well. However, I designed this method so that the parameter passed to minimum could be omitted, in which case the array element itself is used as the comparison value, e.g.
var array = [3, 4, 1, 9]
var min = array.minimum()
The compiler hates this. It says "Cannot convert the expression's type () to Int?". I'm clueless here. Any thoughts?
(As a quick aside, the reason for the parameter is if you want to compare object by, say, the value of a property, e.g., routes.map( { $0 as MKRoute }).minimum({ $0.distance })
will give you the route with the minimum distance.)