您的位置:首页 > 移动开发 > Swift

swift 闭包 tips

2016-11-01 23:12 232 查看
简化版的闭包,记住用$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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: