Duncan Rowland Duncan Rowland - 20 days ago 8
Swift Question

Swift Map Sorted Closure

I am trying to understand closures in swift and am missing something fundamental.

Given the following example:

var numbers = [20, 19, 7, 12]
numbers.map({(number: Int) -> Int in return 3 * number})
numbers.map {(number: Int) -> Int in return 3 * number}
numbers.sorted {(n1:Int, n2:Int) -> Bool in return n1 < n2}


Why do the extra braces work for map but not sorted?
i.e.

numbers.sorted({(n1:Int, n2:Int) -> Bool in return n1 < n2})


does not compile...

"error: argument passed to call that takes no arguments"


Please could someone could explain the difference? Thanks.

Avt Avt
Answer

Because sort method is func sorted(by:). So you have to add by param name:

numbers.sorted(by: {(n1:Int, n2:Int) -> Bool in return n1 < n2})