swift 闭包 tips

简化版的闭包,记住用$0 $1代替表达式




import UIKit

import CoreSpotlight



var numberArry = [12,24,54,14,53,5,1]


var alreadySort = numberArry.sorted(by:{n1,n2 in n1>n2})


print(alreadySort)


var alreadySorted = numberArry.sorted(by:{$0<$1})


print(alreadySorted)


var sortedAgain = numberArry.sorted(by:>)


print(sortedAgain)


var stringArry = ["alex","b","ced","dick"]


var sortString = stringArry.sorted(by:>)


print (sortString)

// if closure is the last arguent, you can go bleow

var longlong = numberArry.sorted(){

    (n1:Int,n2:Int)->Bool in return n1 > n2

}


var longAndlong = numberArry.sorted(){

    $0 > $1

}


// actually if closure is the only argument, you can go below


var longlonglong = numberArry.sorted{$0>$1}



// Below example shows the map method for Array using closure as only arg


// first create an dictionary


var dic = [1:"one",2:"two",3:"three",4:"four",5:"five",6:"six",7:"seven",8:"eight",9:"nine",0:"zero"]


// then the number array which you want to transimit to string array


var num = [12,302,200,8,80]


var string = num.map{

    (number)->String in

    var temp_numb=number

    var string=""

    repeat{

        string = dic[temp_numb%10]! + string

        temp_numb /= 10

    }while temp_numb>0

    return string

}

print(string)



// colosure is reference type

// closure can be escaped(当作为参数时,它能在函数外面调用,但要加@escaping

// 因为closure时引用类型,不是值传递?

// you should put in var outside function to keep the closure


var outHandler:[()->Void] = [] //一个包含闭包的数组


//@escaping similar to inout but it only used for function type

func containClosure(singleOne:@escaping ()->Void){

    outHandler.append(singleOne)

}



// normally closure will be called when put as parameter in function

// but you can put @escaping toi escape

// making closure escaping, you need to explicitly put self in object

func noEscape(singleOne: () -> Void ){

    // outHandler.append(singleOne) // it will fail because it escaped

    singleOne()

}


print("xx")

class test{

    var x = 10

    func doSomgthing(){

    containClosure{ self.x = 100 }

    noEscape{ x = 200 }

    }

}


test().doSomgthing()


print(test().x)


print("xxx")




var outHandler:[()->Void] = [] //一个包含闭包的数组


func containClosure(singleOne:@escaping ()->Void){

    outHandler.append(singleOne)

}



func noEscape(singleOne: () -> Void ){

    // outHandler.append(singleOne) // it will fail because it escaped

    singleOne()

}


class test{

    var x = 10

    func doSomgthing(){

    containClosure{ self.x = 100 }

    noEscape{ x = 200 }

    }

}


var x = test()

x.doSomgthing()


print(x.x)


outHandler.first?()


print(x.x)







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值