Closure
First Class Function
func toStr(x: Int) -> String {
return "(x)"
}
toStr(3)
// functions can be assigned to a variable.
let toStr2 = {
(x: Int) -> String in
return "(x)"
}
toStr2(4)
Syntax Sugar
Pass a function as a parameter
let toStr = {
(x: Int) -> String in
return "(x)"
}
let toStr2 = {
(x: Int) -> String in
return "a(x)"
}
toStr(5)
toStr2(5)
func ajax(callback: (x: Int) -> String) {
callback(x: 10)
}
ajax(toStr) // 10
ajax(toStr2) // a10
type of the function

((x:Int) -> String)
lambda calculas
ajax({(param: Int) -> String in
return “(param)”
})
ajax({(param: Int) -> String in
return “($0)”
})
ajax({(param: Int) -> String in
return “($0)”
})
ajax(){“($0)”}
Complete
Short Hand
Closure
var result = 0 // caller’s result
ajax({
result++
})
func ajax(callback: ()->()) {
var result = 10 // nothing to do with the caller’s result
callback()
callback()
}
println(result) // 2, not 12
Callback
var result: String
ajax(
{
result = $0
},
fail:{
result = “NG”
}
)
func ajax(ok: (x:String)->(), fail fail:()->()) {
if let ret = get_string_via_ajax()
{
ok(x:ret)
} else {
fail()
}
}
map (transformer)
let list = [1, 2, 3]
list.map({$0 x 3}) // [3, 6, 9]
list.map(){$0 x 3}
list.map{$0 x 3}

Swift study: Closure

  • 1.
  • 2.
    First Class Function functoStr(x: Int) -> String { return "(x)" } toStr(3) // functions can be assigned to a variable. let toStr2 = { (x: Int) -> String in return "(x)" } toStr2(4) Syntax Sugar
  • 3.
    Pass a functionas a parameter let toStr = { (x: Int) -> String in return "(x)" } let toStr2 = { (x: Int) -> String in return "a(x)" } toStr(5) toStr2(5) func ajax(callback: (x: Int) -> String) { callback(x: 10) } ajax(toStr) // 10 ajax(toStr2) // a10 type of the function ((x:Int) -> String)
  • 4.
    lambda calculas ajax({(param: Int)-> String in return “(param)” }) ajax({(param: Int) -> String in return “($0)” }) ajax({(param: Int) -> String in return “($0)” }) ajax(){“($0)”} Complete Short Hand
  • 5.
    Closure var result =0 // caller’s result ajax({ result++ }) func ajax(callback: ()->()) { var result = 10 // nothing to do with the caller’s result callback() callback() } println(result) // 2, not 12
  • 6.
    Callback var result: String ajax( { result= $0 }, fail:{ result = “NG” } ) func ajax(ok: (x:String)->(), fail fail:()->()) { if let ret = get_string_via_ajax() { ok(x:ret) } else { fail() } }
  • 7.
    map (transformer) let list= [1, 2, 3] list.map({$0 x 3}) // [3, 6, 9] list.map(){$0 x 3} list.map{$0 x 3}