SwiftyFinch
SwiftyFinch

Reputation: 475

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 { }

Upvotes: 5

Views: 214

Answers (1)

Martin R
Martin R

Reputation: 539685

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 { }

Upvotes: 7

Related Questions