argument names will be derived. Since the shorthand argument is defined in expression
body the 'in' keyword is omitted.
Closures as Operator Functions
Swift provides an easy way to access the members by just providing operator functions as
closures. In the previous examples keyword 'Bool' is used to return either 'true' when the
strings are equal otherwise it returns 'false'.
The expression is made even simpler by operator function in closure as
let numb = [ 98 , - 20 , - 30 , 42 , 18 , 35 ]
var sortedNumbers = numb.sorted({
(left: Int, right: Int) - > Bool in
return left < right
})
let asc = numb.sorted(<)
println(asc)
When we run the above program using playground, we get the following result:
[-30, -20, 18, 35, 42, 98]
Closures as Trailers
Passing the function's final argument to a closure expression is declared with the help of
'Trailing Closures'. It is written outside the function () with {}. Its usage is needed when
it is not possible to write the function inline on a single line.
reversed = sorted(names) { $0 > $1}
where {$0 > $1} are represented as trailing closures declared outside (names).
import Foundation
var letters = ["North", "East", "West", "South"]
let twoletters = letters.map({ (state: String) - > String in
return state.substringToIndex(advance(state.startIndex, 2 )).uppercaseString
})
let stletters = letters.map() { $0.substringToIndex(advance($0.startIndex,
2 )).uppercaseString }
println(stletters)