birdy 發表於 2016-8-8 20:21:05

有關 func 和 closure 寫法

本帖最後由 birdy 於 2016-8-8 23:34 編輯

func test(n1:Int, n2:Int, s1:String) {

print("/(s) is /(n1+n2")

}


test(100, n2:200, s:"John")-->第一個參數不寫名稱,後面一定要寫。

換成 closure 則先是把func test1 這名字拿掉, 然後把 { 拿到最前面 , 再於主要執行程式碼前方加上 in 。

var testClosure = { (n1:Int, n2:Int, s1:String)in

print("/(s) is /(n1+n2")

}

testClosure(100,200,"John") --> 參數絕不可寫名字出來

closure更省略的寫法:

var testClosure : (Int, Int, String) -> () = {// 無論有無回傳值都要寫出來
print("/($2) is /($0+$1)")
}

但如果參數有名稱如:var testClosure : (a:Int, b:Int, c:String) 則一定全部寫出來,包括第一個。例如 :testClosure(a:10, b:20, c:"hello")
反之如無名稱自然不必寫。有的有名字有的沒名字,有名就要寫。
頁: [1]
查看完整版本: 有關 func 和 closure 寫法