Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 { }
like image 995
SwiftyFinch Avatar asked Aug 14 '17 06:08

SwiftyFinch


1 Answers

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 { }
like image 166
Martin R Avatar answered Sep 30 '22 04:09

Martin R