funcsquare(number:Int) ->Int
{
returnnumber * number
}
square(number:10)
letsquareClosuren =
{
(number:Int) ->Intin
returnnumber * number
}
squareClosuren(10)
//例子1
letdemo = {print("Hello 闭包")}
demo()
//计算两个数的商
letdivide =
{
(num1:Int,num2:Int) ->Intin
returnnum1/num2
}
divide(100,10)
//闭包表达式 肯定是{}包括住的,
//{(partmeters) -> (return type)in
//statements
//}
funcgetScore(score:[Int], con : (Int)->Bool) -> [Int]
{
//定义一个新的数组
varnewScore:[Int] = [Int]()
foriteminscore
{
ifcon(item)
{
newScore.append(item)
}
}
returnnewScore
}
//--------------四种闭包简写方式---------------------------
//print(getScore(score: [65,75,85,95],con : {(s: Int)->Bool in return s>80}))
//print(getScore(score: [65,75,85,95],con : {(s: Int)in return s>80}))将尖头去掉
//print(getScore(score: [65,75,85,95],con : {s in return s>80}))省略参数类型
//print(getScore(score: [65,75,85,95],con : {s in s>80})) 省略return关键字
//利用$0关键字
print(getScore(score: [65,75,85,95],con : { $0>80}))
letarr = [65,75,85,95]
print(arr.filter({$0 >60}))
arr.forEach
{(s)inprint(s)}
funcmakeIncrementor(forIncrement amount:Int) -> () ->Int
{
varrunningTotal =0
funcincrementor() ->Int
{
runningTotal += amount
returnrunningTotal
}
returnincrementor
}
leta = makeIncrementor(forIncrement:10)
a()
a()
a()