1.函數的基本形式函數
func greetAgain(person: String) -> String {spa
return "Hello again, " + person + "!"it
}io
print(greetAgain(person: "Anna"))class
2.用元組做爲返回值標籤
func minMax(array: [Int]) -> (min: Int, max: Int) {co
var currentMin = array[0]let
var currentMax = array[0]return
for value in array[1..<array.count] {參數
if value < currentMin {
currentMin = value
} else if value > currentMax {
currentMax = value
}
}
return (currentMin, currentMax)
}
3.參數標籤
全部的參數都必須有一個獨一無二的名字。雖然多個參數擁有一樣的參數標籤是可能的,可是一個惟一的函數標籤可以使你的代碼更具可讀性
print(greetAgain(person: "Anna"))
4.參數能夠帶默認值
func someFunction(parameterWithoutDefault: Int, parameterWithDefault: Int = 12) {
// 若是你在調用時候不傳第二個參數,parameterWithDefault 會值爲 12 傳入到函數體中。
}
someFunction(parameterWithoutDefault: 3, parameterWithDefault: 6) // parameterWithDefault = 6
someFunction(parameterWithoutDefault: 4) // parameterWithDefault = 12
5.可變參數
一個函數最多擁有一個可變參數
func arithmeticMean(_ numbers: Double...) -> Double {
var total: Double = 0
for number in numbers {
total += number
}
return total / Double(numbers.count)
}
6.輸入輸出參數
注意調用函數的時候用&符號
func swapTwoInts(_ a: inout Int, _ b: inout Int) {
let temporaryA = a
a = b
b = temporaryA
}
var someInt = 3
var anotherInt = 107
swapTwoInts(&someInt, &anotherInt)
print("someInt is now \(someInt), and anotherInt is now \(anotherInt)")