Home > AI > Language > Swift >

closure

{ (parameters) -> return type in
    statements
}

Example 1:

let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]

// pass function
func backward(_ s1: String, _ s2: String) -> Bool {
    return s1 > s2
}
var reversedNames = names.sorted(by: backward)


// closure
reversedNames = names.sorted(by: { (s1: String, s2: String) -> Bool in
    return s1 > s2
})


// infer type
reversedNames = names.sorted(by: { s1, s2 in return s1 > s2 } )


// infer return
reversedNames = names.sorted(by: { s1, s2 in s1 > s2 } )


// shorhand argument names
reversedNames = names.sorted(by: { $0 > $1 } )

// operator method
reversedNames = names.sorted(by: >)

print(reversedNames)


Trailing closure:

func funcWithClosure(closure: () -> Void) {
    // function body goes here
}


// without using trailing closure
funcWithClosure(closure: {
    // closure's body goes here
})


// trailing closure
funcWithClosure() {
    // trailing closure's body goes here
}

return a closure

func makeIncrementer(forIncrement amount: Int) -> () -> Int {
    var runningTotal = 0
    func incrementer() -> Int {
        runningTotal += amount
        return runningTotal
    }
    return incrementer
}

Leave a Reply