总结知识点:
/************OC中Block********************/
//1、无参数无返回值 void(^blockName)(void) = ^{};
//2、有参数无返回值: void(^blockName1)(NSString * name) = ^(NSString * name){};
//3、无参数有返回值: NSString *(^blockName2)(void)=^{return Type};
//4、有参数有返回值: NSString *(^blockName3)(NSString * name)=^(NSString * name){ return Type};
/************Swift闭包********************/
//1、无参数无返回值 let 变量名 = { ()->() in code }
//2、有参数无返回值: let 变量名 = { (_ name:String)->() in code }
//3、无参数有返回值: let 变量名 = { ()->String in code } 或者 let 变量名 = { ()->(String,String) in code }
//4、有参数有返回值: let 变量名 = { (_name:String)->String in code } 或者 let 变量名 = { (_name:String,_sex:String)->(String,String) in code }
//带参数的闭包的通用形式://取出func 的带参数的函数形式,但是函数的{} 换成了in ,函数的实现,写在in的后面,in就相当于block中的{}
//通用的形式
// {
// (parameters) -> returnType in
// code
// }
具体的实例操作:
//最简单的闭包:函数name()->() 无参数的Block void(^blockName)(void) = ^{}
let b1 = {
print("hello");
}
//带参数的闭包
let b2 = {(_ name:String) ->() in //()可以使用Void代替
print(name);
}
//带参数带返回值:
let b3 = {
(_ name:String)-> String in
return String.init(format:"%ld=====%@", 2,name);
}
//带有多个参数:
let b4 = {
(_ name1:String,_ name2:String)-> (String,String) in
return (String.init(format:"%ld=====%@", 2,name1),String.init(format:"%@=====%@", "傻丫头",name2));
}
//没有参数,有多个返回值:
let b5 = { ()->(String,String) in
return ("张三","李四");
}
//作为参数:
func testClose(blockName:Block) -> Void {
let (name1,name2) = blockName();
print(name1,name2);
}
相应的调用方式:(为方便操作,将以上内容,写在了一个单例中)
SwiftTool.singleton.b1();
SwiftTool.singleton.b2("小萌");
let name:String = SwiftTool.singleton.b3("小萌");
print(name);
let (name1,name2):(String,String) = SwiftTool.singleton.b4("小鱼儿","花无缺") ;
print(name1,name2);
let (sex1,sex2) = SwiftTool.singleton.b5();
print(sex1,sex2);
/****几种调用方式:***/
//第一种方式:
SwiftTool.singleton.testClose { () -> (String, String) in
//函数主体
return("李四","张三");
};
//第二种方式:
SwiftTool.singleton.testClose(blockName: { () -> (String, String) in
//闭包主体
return("李四","张三");
});
//第三种方式:
SwiftTool.singleton.testClose (blockName: {
//闭包主体
return("李四","张三");
});
//第四种方式:尾随闭包
SwiftTool.singleton.testClose (){
//闭包主体
return("李四","张三");
};