1.闭包
可以通过定义属性或者定义方法进行回调的操作
1️⃣无参无返回值
typealias funcBlock = () -> ()
(1)定义属性
var parameterBlock : funcBlock?
if parameterBlock != nil{
parameterBlock!();
}
对应的调用
block.parameterBlock = {() -> () in
print("无参无返回值")
}
(2)定义成方法
func testBlock(blockfunc: funcBlock!){
if (blockfunc) != nil{
blockfunc()
}
}
对应的调用
block.testBlock {
print("-------func--------")
}
2️⃣有参无返回值
typealias callBackBlock = (_ index : String ) -> ()
func callBackFuncBlock(blockfunc: callBackBlock!) {
if blockfunc != nil{
blockfunc("I am Amy")
}
}
对应的回调
block.callBackFuncBlock { (res: String) in
print(res);
}
//打印结果:I am Amy
3️⃣有参数有返回值
typealias paramBlock = (Int) -> String //返回值类型是字符串
func paramFuncBlock(blockfunc: paramBlock!) {
if blockfunc != nil{
let retFunc = blockfunc(5)
print("Block\(retFunc)")
}
}
对应的回调
block.paramFuncBlock { (res: Int) -> String in
return "res: \(res)*50"
}
4️⃣返回值是一个函数指针,入参为String
typealias funcBlockB = (Int,Int) -> (String)->()
func testBlockB(blockfunc: funcBlockB!) {
if blockfunc != nil {
let retFunc = blockfunc(9,10)
retFunc("The Result is")
}
}
对应的回调
block.testBlockB { (a: Int, b:Int) -> (String) -> () in
func callBackFunc(res: String) {
print("\(res) : \(a) + \(b) = \(a+b)")
}
return callBackFunc
}
//打印结果:The Result is : 9 + 10 = 19
5️⃣返回值是一个函数指针,入参为String 返回值也是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)")
}
}
对应的回调
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
}
//打印结果: The Result is 9 + 10 = 19
以上🍓