swift中闭包block的使用

前端之家收集整理的这篇文章主要介绍了swift中闭包block的使用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

使用闭包block的方式,一是定义成函数方式,二是定义成属性变量。

方法1:定义成属性变量

  1. // 1
  2. // block定义
  3. typealias BlockTarget = (String) -> (Void)
  4. // 定义成变量
  5. var blockTarget:BlockTarget?
  6. //
  7. self.blockTarget = { text -> Void in
  8. print("text = \(text)")
  9. }
  10. //
  11. self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "block",style: .Done,target: self,action: Selector("blockClick"))
  12. //
  13. func blockClick()
  14. {
  15. self.blockTarget?("block click")
  16. }

  1. // 2
  2. //
  3. var blockAction:((String) -> (Void))?
  4. //
  5. self.blockAction = { text -> Void in
  6. print("action = \(text)")
  7. }
  8. //
  9. self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "block",action: Selector("blockClick"))
  10. //
  11. func blockClick()
  12. {
  13. self.blockAction?("black action")
  14. }


方法2:定义成函数

1、无参数的函数

  1. // 无参数
  2. func blockHandle(handle:(Void) -> Void)
  3. {
  4. print("block方法:没有参数的……")
  5. handle()
  6. }
  7. // 使用
  8. self.blockHandle {
  9. () -> Void in
  10. print("block方法:没有参数的……")
  11. }


2、带参数的函数

  1. // 带参数
  2. func resultImageUrl(url url:String,handle:(NSURL) -> Void)
  3. {
  4. let nsurl = NSURL(string: url)
  5. print("NSURL = \(nsurl)")
  6. handle(nsurl!)
  7. }
  8. // 使用
  9. self.resultImageUrl(url: "http://www.hao123.com") {
  10. (url:NSURL) -> Void in
  11. print("url is \(url)")
  12. }

猜你在找的Swift相关文章