1.閉包
可以通過定義屬性或者定義方法進(jìn)行回調(diào)的操作
1??無參無返回值
typealias funcBlock = () -> ()
(1)定義屬性
var parameterBlock : funcBlock?
if parameterBlock != nil{
parameterBlock!();
}
對(duì)應(yīng)的調(diào)用
block.parameterBlock = {() -> () in
print("無參無返回值")
}
(2)定義成方法
func testBlock(blockfunc: funcBlock!){
if (blockfunc) != nil{
blockfunc()
}
}
對(duì)應(yīng)的調(diào)用
block.testBlock {
print("-------func--------")
}
2??有參無返回值
typealias callBackBlock = (_ index : String ) -> ()
func callBackFuncBlock(blockfunc: callBackBlock!) {
if blockfunc != nil{
blockfunc("I am Amy")
}
}
對(duì)應(yīng)的回調(diào)
block.callBackFuncBlock { (res: String) in
print(res);
}
//打印結(jié)果:I am Amy
3??有參數(shù)有返回值
typealias paramBlock = (Int) -> String //返回值類型是字符串
func paramFuncBlock(blockfunc: paramBlock!) {
if blockfunc != nil{
let retFunc = blockfunc(5)
print("Block\(retFunc)")
}
}
對(duì)應(yīng)的回調(diào)
block.paramFuncBlock { (res: Int) -> String in
return "res: \(res)*50"
}
4??返回值是一個(gè)函數(shù)指針楔壤,入?yún)镾tring
typealias funcBlockB = (Int,Int) -> (String)->()
func testBlockB(blockfunc: funcBlockB!) {
if blockfunc != nil {
let retFunc = blockfunc(9,10)
retFunc("The Result is")
}
}
對(duì)應(yīng)的回調(diào)
block.testBlockB { (a: Int, b:Int) -> (String) -> () in
func callBackFunc(res: String) {
print("\(res) : \(a) + \(b) = \(a+b)")
}
return callBackFunc
}
//打印結(jié)果:The Result is : 9 + 10 = 19
5??返回值是一個(gè)函數(shù)指針叹括,入?yún)镾tring 返回值也是String
typealias funcBlockC = (Int,Int) -> (String)->String
func testBlockC(blockfunc: funcBlockC!) {
if (blockfunc) != nil {
let retfunc = blockfunc(9,10)
let str = retfunc("The Result is")
print("\(str)")
}
}
對(duì)應(yīng)的回調(diào)
block.testBlockC { (a: Int, b: Int) -> (String) -> String in
func sumFunc(res: String) -> String {
let resNum = a + b
return "\(res) \(a) + \(b) = \(resNum)"
}
return sumFunc
}
//打印結(jié)果: The Result is 9 + 10 = 19
以上??