As an exercise in learning Swift, I'm trying to write minimum and maximum functions for arrays, as shown below:
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!, <)
}
}
I missed the maximum function because it is the same, at least, but with a different operator passed to comparest. I tested the function comparestand it works well, for example.
var array = [4, 2, 3]
var min = array.comparest({ $0 }, <)!
The value of min is 2.
My problem is that the compiler does not like my function minimum. He shows an angry red mistake on the line self.comparest(comparator!, <)and says: "Partial application of the universal method is not allowed." I have written enough Haskell to find out what a partial application is, but for me it does not look like a partial application. All arguments are specified.
?