Skip to content

Instantly share code, notes, and snippets.

@mosluce
Last active August 18, 2016 04:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mosluce/a0800aa74ab5fa162ab7bd02b7f4b46b to your computer and use it in GitHub Desktop.
Save mosluce/a0800aa74ab5fa162ab7bd02b7f4b46b to your computer and use it in GitHub Desktop.
Swift Closure: How / Why - 剛開始接觸 Closure 應該很多人被書裡寫的弄到頭昏腦脹,不知道到底怎樣寫才對,這邊用案例說明
//: Playground - noun: a place where people can play
import UIKit
var closure: ((a: Int, b: Int) -> Int)!
//基本型
closure = {(a: Int, b: Int) -> Int in
return a + b
}
//DEMO
print(closure(a: 1, b: 2))
//型別省略型
closure = { a, b in
return a + b
}
//DEMO
print(closure(a: 1, b: 2))
//return 省略型
closure = { a, b in a + b + 1}
//DEMO
print(closure(a: 1, b: 2))
//參數省略型 (因為沒有參數所以也不用 in)
//其中 $0 代表第一個參數, $1 代表第二個參數, $2...會錯...因為沒有第三個參數XD...總之以此類推
closure = { $0 * 10 + $1 }
//DEMO
print(closure(a: 1, b: 2))
//以下為錯誤示範
/**
錯誤原因:前後文完全無法判斷型別
上面的範例「型別省略型」為什麼可以?
因為在宣告的時候 "var closure: ((a: Int, b: Int) -> Int)!"
已經指定好所有的型別了
*/
//let closure1 = { a, b in
//return a + b
//}
/**
如果是下面這樣就可以
Why: Swift 裡面 + - * / 是不會自動轉型的
所以 Int 只能和 Int 運算
因此可以推斷 a 和 b 都是 Int,以致於 return 也是 Int
*/
let closure1_ok = { a, b in
return a + b + 1
}
//所以這樣也是對的,原理同上
let closure1_ok_double = { a, b in
return a + b + 1.0
}
//錯誤示範之2
//錯誤原因同上
//let closure2 = { $0 + $1 }
//正確
//原因還是同上 ˚¬˚
let closure2_ok = { $0 + $1 + 1 }
//所以說 ~ 可上面這個範例還可以 ~
//自由的想放幾個參數就放幾個...不過這種 code 很難維護 you know...
let closure3_ok = { $0 + $1 + $2 + $3 + $4 + 1 }
//以上 Closure
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment