步驟
1.定義一個(gè)帶有閉包參數(shù)的函數(shù)
func doPOST(url: String, commpletehandler: ((String,String) -> Void)?){
if let hander = commpletehandler {
hander( "post","result")
}
}
doPOST("http://www.51.com") { (str1, str2) -> Void in
print(str1)
print(str2)
}
結(jié)果:
post
result
缺點(diǎn):每次處理一樣的邏輯都需要重寫(xiě)閉包里面的內(nèi)容
2.定義一個(gè)和步驟1閉包一樣的函數(shù)披诗,簡(jiǎn)言之蜕该,將閉包抽象成函數(shù)
func doPOST(url: String, commpletehandler: ((String,String) -> Void)?){
if let hander = commpletehandler {
hander( "post","result")
}
}
//MARK:函數(shù)可以當(dāng)閉包使用
func doUrlhander(str1: String, str2: String){
print(str1)
print(str2)
}
doPOST("http://www.baidu.com",commpletehandler: doUrlhander)
結(jié)果:
post
result
優(yōu)點(diǎn):相同的邏輯不用重寫(xiě)
缺點(diǎn):比較死,只能處理一種邏輯
3.定義一個(gè)中間函數(shù),返回值是一個(gè)步驟1的閉包
func doPOST(url: String, commpletehandler: ((String,String) -> Void)?){
if let hander = commpletehandler {
hander( "post","result")
}
}
//柯里化函數(shù)completeHander1 和 completeHander等價(jià)
func completeHander1(str0: String)(str1:String,str2:String){
print(str0)
print(str1)
print(str2)
}
func completeHander(str0: String) -> ((String,String) -> Void){
return {(str1,str2) -> Void in
print(str0)
print(str1)
print(str2)
}
}
doPOST("http://www.google.com.hk", commpletehandler: completeHander1("li"))
結(jié)果:
li
post
reult
優(yōu)點(diǎn):動(dòng)態(tài)產(chǎn)生一個(gè)閉包回調(diào)