Duncan Rowland Duncan Rowland - 1 year ago 119
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?

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 Source

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})
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download