函數(shù)結(jié)構(gòu)
- 函數(shù)結(jié)構(gòu)
func 函數(shù)名(參數(shù))-> 函數(shù)返回類型{
函數(shù)體
}
函數(shù)類型
- 多參數(shù)函數(shù):參數(shù)之間用逗號(,)隔開
func halfOpenRangeLength(start: Int, end: Int) -> Int {
return end - start
}
println(halfOpenRangeLength(1, 10))
// prints "9"
- 無參數(shù)函數(shù):注意巡蘸,即使一個函數(shù)不帶有任何參數(shù)咐蚯,函數(shù)名稱之后也要跟著一對空括號()
func sayHelloWorld() -> String {
return "hello, world"
}
println(sayHelloWorld())
// prints "hello, world"
- 無返回值參數(shù):無返回值函數(shù)后面可以不加返回箭頭( – >)和返回類型
func sayGoodbye(personName: String) {
println("Goodbye, \(personName)!")
}
sayGoodbye("Dave")
// prints "Goodbye, Dave!"
- 多返回值函數(shù):可以使用元組或者多返回值組成的復(fù)合作為返回值健无。
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)
}
外部參數(shù)名
- 使用外部參數(shù)名稱的初衷是為了在別人在調(diào)用函數(shù)時知道函數(shù)入?yún)⒌哪康摹?/li>
func join(string s1: String, toString s2: String, withJoiner joiner: String)
-> String {
return s1 + joiner + s2
}
join(string: "hello", toString: "world", withJoiner: ", ")
// returns "hello, world"
如果一個入?yún)⒓仁莾?nèi)部參數(shù)又是外部參數(shù)旬迹,那么只要在函數(shù)定義時參數(shù)前加#前綴即可火惊。
可變參數(shù)
當(dāng)傳入的參數(shù)個數(shù)不確定時,可以使用可以參數(shù)奔垦,只需要在參數(shù)的類型名稱后加上點字符(...)屹耐。
func arithmeticMean(numbers: Double...) -> Double {
var total: Double = 0
for number in numbers {
total += number
}
return total / Double(numbers.count)
}
arithmeticMean(1, 2, 3, 4, 5)
// returns 3.0, which is the arithmetic mean of these five numbers
arithmeticMean(3, 8, 19)
// returns 10.0, which is the arithmetic mean of these three numbers
注意:函數(shù)最多有一個可變參數(shù)的參數(shù),而且必須出現(xiàn)在參數(shù)列表的最后以避免多參數(shù)調(diào)用時出現(xiàn)歧義宴倍。
輸入輸出參數(shù)
如果想用一個函數(shù)來修改參數(shù)的值张症,并且只在函數(shù)調(diào)用結(jié)束之后修改,則可以使用輸入-輸出參數(shù)鸵贬。只要才參數(shù)定義時添加inout關(guān)鍵字即可表明是輸入輸出參數(shù)俗他。