Swift函數

函數定義html

 

使用 func 定義一個函數。調用函數使用他的名字加 上小括號中的參數列表。使用 -> 分隔參數的名字和 返回值類型。函數

 

函數聲明:spa

 

[html] view plaincopy在CODE上查看代碼片派生到個人代碼片.net

  1. <span style="font-size:14px;">func greet(name: String, day: String) -> String {  指針

  2. return "Hello \(name),today is \(day)."  code

  3.    

  4. </span>  orm


函數調用:greet("Bob", "Tuesday")htm

 

無返回值函數blog

[html] view plaincopy在CODE上查看代碼片派生到個人代碼片ip

  1. <span style="font-size:14px;">func sayGoodbye(personName: String) {  

  2. println("Goodbye, \(personName)!")  

  3. }  

  4. sayGoodbye("Tony")</span>  


多返回值函數

 

使用元組類型返回多個值:

[html] view plaincopy在CODE上查看代碼片派生到個人代碼片

  1. <span style="font-size:14px;">func count(string: String) -> (vowels: Int, consonants:Int, others: Int) {  

  2. var vowels = 0,consonants = 0others0 for character in string {  

  3. switch String(character).lowercaseString {  

  4. case "a","e", "i","o", "u":  

  5. ++vowels  

  6. case "b","c", "d","f", "g", "h", "j", "k", "l", "m","n", "p","q", "r","s", "t", "v", "w","x", "y", "z":  

  7. ++consonants default:  

  8. ++others  

  9. }  

  10. }   

  11. return (vowels, consonants, others)  

  12. }  

  13. let total = count("somearbitrary string!")   

  14. println("\(total.vowels) 元音 , \(total.consonants) 輔 音")</span>  


嵌入函數

 

函數嵌套: 至關於函數指針

 

[html] view plaincopy在CODE上查看代碼片派生到個人代碼片

  1. <span style="font-size:14px;">func chooseStepFunction(backwards: Bool) ->(Int) -> Int {  

  2. func stepForward(input: Int) -> Int { return input  

  3. + 1 }  

  4. func stepBackward(input: Int) -> Int { return input  

  5. - 1 }  

  6. return backwards ? stepBackward : stepForward  

  7. }  

  8. var currentValue = -4  

  9. let               moveNearerToZero                    =  

  10. chooseStepFunction(currentValue> 0)  

  11. while currentValue != 0{  

  12. println("\(currentValue)... ")   

  13. currentValue = moveNearerToZero(currentValue)  

  14. }</span>  

Swift交流討論論壇論壇:http://www.cocoagame.net

歡迎加入Swift技術交流羣:362298485

相關文章
相關標籤/搜索