閱讀410 返回首頁    go 阿裏雲 go 技術社區[雲棲]


Swift函數

函數定義

 

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

 

函數聲明:

 

func greet(name: String, day: String) -> String {
return "Hello \(name),today is \(day)."
 
} 

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

 

無返回值函數

func sayGoodbye(personName: String) {
println("Goodbye, \(personName)!")
}
sayGoodbye("Tony")

多返回值函數

 

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

func count(string: String) -> (vowels: Int, consonants:Int, others: Int) {
var vowels = 0,consonants = 0, others= 0 for character in string {
switch String(character).lowercaseString {
case "a","e", "i","o", "u":
++vowels
case "b","c", "d","f", "g", "h", "j", "k", "l", "m","n", "p","q", "r","s", "t", "v", "w","x", "y", "z":
++consonants default:
++others
}
} 
return (vowels, consonants, others)
}
let total = count("somearbitrary string!") 
println("\(total.vowels) 元音 , \(total.consonants) 輔 音")

嵌入函數

 

函數嵌套: 相當於函數指針

 

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 = -4
let               moveNearerToZero                    =
chooseStepFunction(currentValue> 0)
while currentValue != 0{
println("\(currentValue)... ") 
currentValue = moveNearerToZero(currentValue)
}

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

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



最後更新:2017-04-03 07:57:14

  上一篇:go android的activity棧管理
  下一篇:go Android TextView 實現文字大小不同和文字顏色不同