参考:swift–四种传值(代理、闭包、属性、通知)
https://www.cnblogs.com/adampei-bobo/p/8954042.html
属性
场景:比如从A携带参数到B
如图B中需要获取前一页携带的参数
代理
类型android的接口
例:
第一步:
第二步:在需要传值的地方传值
MySecondViewController().CallBack(back: "123")
通知
安卓中的广播
1.注册通知
NotificationCenter.default.addObserver(self, selector: #selector(endTopicAction(obj:)), name: NSNotification.Name.init("11"), object: nil)
2.添加收到通知后的事件
@objc func endTopicAction(obj:Notification){
print("--------",obj.object!)
}
3.发送
let a = [["A":"aaa"],["B":"bbb"]]
NotificationCenter.default.post(name: NSNotification.Name.EndTopicSuccessNoti, object: a)
4.在注册页要注销
deinit {
NotificationCenter.default.removeObserver(self)
}
闭包
func testClosure(res:()->()){
res()
}
func testClosure(arg1:String,res:()->()) {
res()
}
func testClosure(arg1:String,res:(String)->()) {
res(arg1)
}
func testClosure(arg1:String,res:(String,String)->()) {
res(arg1,"111")
}
func testClosure(arg1:String,res:(String)->(Bool)) {
let b = res(arg1)
print("test4 return :",b)//return false
}
func testClosure(arg1:String,res:(String,String)->(Bool,Bool)) {
let b = res(arg1,"222")
print("test5 return :",b.0,b.1)//return true false
}
测试样例
testClosure(arg1: "test1") {
print("test1:无返回值")
}
//最后一个参数时候 可以尾随闭包
testClosure {
}
testClosure(){
}
//不是尾随闭包
testClosure(res: {
})
let block:(String,String)->() = {
res1 ,res2 in
print(res1,res2)
}
testClosure(arg1: "aa", res: block)
testClosure(arg1: "test2") { (result) in
print("test2:",result)
}
testClosure(arg1: "test3") { (res1, res2) in
print("test3:",res1,res2)
}
testClosure(arg1: "test4") { (res3) -> (Bool) in
print("test4:",res3)
return false
}
testClosure(arg1: "test5") { (res4, res5) -> (Bool, Bool) in
print("test5:",res4,res5)
return (true,false)
}
//
// test1:无返回值
// test2: test2
// test3: test3 111
// test4: test4
// test4 return : false
// test5: test5 222
// test5 return : true false
// print({"1" "2" in "1"+"2"})
类似block用法
A页面
let vc = DetailsViewController();
vc.block = {
a1,a3 in
print("22222222222",a1,a3)
}
B页面(DetailsViewController)
var block:((String,String)->())?
block?("12", "we")