Search code examples
swiftfunctionclosuresoperatorsdefault

Can I use an operator as default function argument in Swift?


I'm trying to use operator > as default function argument:

Playground execution failed: error: StackSorting.playground:27:63: 
error: expected expression after unary operator
func sort<T>(..., compare: (T, T) -> Bool = >) where T: Comparable { }
                                            ^

I solved it, but... Does somebody know a shorter way?

func sort<T>(..., compare: (T, T) -> Bool = { $0 > $1 }) where T: Comparable { }

Solution

  • You can use the operator as default value for the parameter, you only have to enclose it in parentheses:

    func sort<T>(..., compare: (T, T) -> Bool = (>)) where T: Comparable { }