swift基礎文法三(函數與閉包)

來源:互聯網
上載者:User

標籤:

 1 // Playground - noun: a place where people can play 2  3 import Cocoa 4 //函數和閉包 5  6 //函數,使用func關鍵字聲明函數: 7 func greet(name:String, day:String) -> String { 8     return "Hello \(name), today is \(day)." 9 }10 greet("Bob", "Tuesday")11 12 13 //通過元組(Tuple)返回多個值14 func getGasPrices() -> (Double, Double, Double){15     return (3.59, 3.69, 3.79)16 }17 getGasPrices()18 19 //支援帶有變長參數的函數20 func sumOf(numbers: Int...) -> Int {21     var sum = 022     for number in numbers {23         sum += number24     }25     return sum26 }27 28 sumOf()29 sumOf(42, 597, 12)30 31 //函數也可以嵌套32 func returnFifteen() -> Int {33     var y = 1034     func add() {35         y += 536     }37     add()38     return y39 }40 41 returnFifteen()42 43 //作為頭等對象,函數既可以作為傳回值,也可以作為參數傳遞44 45 func makeIncrementer() -> (Int -> Int) {46     func addOne(number: Int) -> Int {47         return 1 + number48     }49     return addOne50 }51 var increment = makeIncrementer()52 increment(7)53 54 func hasAnyMatches(list: Int[], condition: Int -> Bool) -> Bool {55     for item in list {56         if condition(item) {57             return true58         }59     }60     return false;61 }62 63 func lessThanTen(number: Int) -> Bool {64     return number < 1065 }66 var numbers = [20, 19, 7, 12]67 hasAnyMatches(numbers, lessThanTen)68 69 //閉包--本質上來說,函數是特殊的閉包,Swift中可以利用{}聲明匿名閉包70 71 numbers.map({72     (number: Int) -> Int in73     let result = 3 * number74     return result75     })76 //當閉包的類型已知時,可以使用下面的簡化寫法77 numbers.map({ number in 3 * number })78 //此外還可以通過參數的 位置來使用參數,當函數最後一個參數是閉包時,可以使用下面的文法:79 sort([1, 5, 3, 12, 2]) {$0 > $1}

 

swift基礎文法三(函數與閉包)

相關文章

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.