Swift中文教程(四)--函數與閉包

來源:互聯網
上載者:User

Function 函數

  Swift使用func關鍵字來聲明函數,函數通過函數名加小括弧內的參數列表來調用。使用->來區分參數名和傳回值的類型:

1 func greet(name: String, day: String) -> String {2     return "Hello \(name), today is \(day)."3 }4 greet("Bob", "Tuesday")

練習:

remove day參數,增加一個參數,比如:今天的午餐特色菜~

1 func greet(name:String, day:String) -> String{2 3   return "Hello \(name), today is \(day)."  //第二章說過用\()來內嵌變數4 5 }6 7 greet('Joe', '菩提玉齋')

 

 

  函數使用元組(tuple)來返回多個值:

1 func getGasPrices() -> (Double, Double, Double) {2     return (3.59, 3.69, 3.79)3 }4 getGasPrices()

 

  函數還可以接收可變的參數個數,將這些參數收集在數組裡面:

1 func sumOf(numbers: Int...) -> Int {2     var sum = 03     for number in numbers {4         sum += number5     }6     return sum7 }8 sumOf()9 sumOf(42, 597, 12)

練習:

編寫一個函數並求出其參數的平均值。

 

  函數是可以嵌套的,嵌套過的函數可以訪問到外部函式宣告過的變數,使用函數嵌套可以便於你組織過長或複雜的函數:

1 func returnFifteen() -> Int {2     var y = 103     func add() {4         y += 55     }6     add()7     return y8 }9 returnFifteen()

 

  在Swift中,函數是第一等類型,這意味著一個函數可以將另外一個函數作為它的傳回值:

1 func makeIncrementer() -> (Int -> Int) {2     func addOne(number: Int) -> Int {3         return 1 + number4     }5     return addOne6 }7 var increment = makeIncrementer()8 increment(7)

 

  函數還能接收其它函數作為它的參數:

 1 func hasAnyMatches(list: Int[], condition: Int -> Bool) -> Bool { 2     for item in list { 3         if condition(item) { 4             return true 5         } 6     } 7     return false 8 } 9 func lessThanTen(number: Int) -> Bool {10     return number < 1011 }12 var numbers = [20, 19, 7, 12]13 hasAnyMatches(numbers, lessThanTen)

  

  Closure 閉包

  

  函數其實是一種閉包的特殊情況,你可以寫一個用花括弧{}包裹的匿名閉包,用in來區分參數與主體的傳回型別:

1 numbers.map({2     (number: Int) -> Int in3     let result = 3 * number4     return result5     })

練習:

重寫這個閉包來對所有奇數返回0

 

  閉包有多種簡潔的寫法。當傳回值類型已知時,比如委託回調,你就可以省略它的參數類型,它的傳回值類選,或者二者都略去,單行語句的閉包可以直接隱式地返回此一語句的值:

1 numbers.map({ number in 3 * number })

 

  你可以通過數字而不是名字來引用一個參數,這對於很短的閉包非常有用。一個閉包通過圓括弧傳遞其最後一個參數到函數能立即生效:

1 sort([1, 5, 3, 12, 2]) { $0 > $1 }

 

 

謝謝,Swifter-QQ群:362232993,同好者進~ 

github地址:https://github.com/Joejo/Swift-lesson-for-chinese

 

 

 

 

 

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.