swift基礎文法(四) 函數、閉包(Closures)

來源:互聯網
上載者:User

標籤:

//函數基本定義func 函數名(參數名:參數類型=預設值)  ->傳回值類型{代碼塊}//無參無傳回值函數func hsmin(){}//單參無傳回值函數func prin(st:String){    println(st)}prin("111")//111func yuanzu(tup:(String,Int)){    print("Int:\(tup.1)  String:\(tup.0)")}yuanzu(("馮小剛",1))//Int:1  String:馮小剛//多參無傳回值函數func addp(a:Int,b:Int){    println(\(a+b))}addp(1,2)//3//單參傳回值函數func prt(l:Int)->Int{    return l+1}println("\(prt(2)")//3//多參傳回值函數func add(a: Int , b : Int) -> Int{    return a+b}func del(a : Int, b : Int) -> Int{    return a-b}println(add(3,4))//7//參數預設值func sum( a : Int, b : Int = 1) -> Int{    return a+b}println(sum(3))//4//輸出參數func swapTwoInts(inout a: Int, inout b: Int) {    let temporaryA = a    a = b    b = temporaryA}var someInt = 3var anotherInt = 107swapTwoInts(&someInt, &anotherInt)println("someInt is now \(someInt), and anotherInt is now \(anotherInt)")//函數嵌套(匿名函數)func chooseStepFunction(backwards: Bool) -> (Int) -> Int {    func stepForward(input: Int) -> Int { return input + 1 }    func stepBackward(input: Int) -> Int { return input - 1 }    return backwards ? stepBackward : stepForward}var currentValue = -4let moveNearerToZero = chooseStepFunction(currentValue > 0)// moveNearerToZero now refers to the nested stepForward() functionwhile currentValue != 0 {    println("\(currentValue)... ")    currentValue = moveNearerToZero(currentValue)}println("zero!")// -4...// -3...// -2...// -1...// zero!

   個人感覺閉包(Closures)相當於c裡面的block只不過在block的基礎上重新改良了一下而已

// 閉包的完整寫法{ ( 參數列表 ) -> 傳回型別 in 代碼塊 }//egvar a : Array = [3,1,4,2,5,7,6]var b = sort( a, { (i1 : Int, i2 : Int) -> Bool in retern i1>i2 })//b=[1,2,3,4,5,6,7]//swift支援類型識別故簡寫為var b = sort( a, {i1, i2 in retern i1>i2})//b=[1,2,3,4,5,6,7]//還可以使用參數識別$0,$1var b = sort( a,{ $0 > $1})//b=[1,2,3,4,5,6,7]//無參無傳回值閉包func someFunctionThatTakesAClosure(closure: () -> ()) {    代碼塊} someFunctionThatTakesAClosure({    代碼塊    }) someFunctionThatTakesAClosure() {    代碼塊}

 

swift基礎文法(四) 函數、閉包(Closures)

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.