加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift闭包的理解

发布时间:2020-12-14 01:42:25 所属栏目:百科 来源:网络整理
导读:1.闭包分三种: 1)全局函数,本身有名字,但是不capture变量 2)嵌套函数,有名字,可以capture变量,但是不可改变 3)闭包表达式,没有名字,可以根据上下文capture变量 2.嵌套函数 func function3(paras : Int ) -(() - Int ){ var total = 0 ; func add()

1.闭包分三种:

1)全局函数,本身有名字,但是不capture变量

2)嵌套函数,有名字,可以capture变量,但是不可改变

3)闭包表达式,没有名字,可以根据上下文capture变量


2.嵌套函数

func function3(paras : Int) ->(() ->Int){

var total = 0;

func add() ->Int{

total = total + paras;

print("totoal = " + String(total));

return total;

}

return add;

}


//闭包内对total 进行capture

let a = self.function3(10);//获得函数a

var b = a();//第一次调用 total =10

b = a();//第二次调用20

b = a();//第三次调用30

print(b);


3.闭包表达式


定义一个数字到英文的对应map

let digitNames = [

0: "Zero",1: "One",2: "Two",3: "Three",4: "Four",

5: "Five",6: "Six",7: "Seven",8: "Eight",9: "Nine"

];

let nums = [123,134,23];

num不必指明类型,可以上下文判断类型,数组map函数的作于是对每一个元素执行闭包中的代码然后返回对于映射的值,最后这些值组成一个数组返回

let strings = nums.map { (var num) -> String in

var output = "";

while num > 0{

output = digitNames[num%10]! + output;

num /= 10;

}

return output;

};

print(strings);

strings的打印结果:

["OneTwoThree","OneThreeFour","TwoThree"]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读