重新閱讀了Swift中文文檔的函數(shù)章節(jié)勋拟,
總結(jié)出以下文檔中提到的13種函數(shù)怔软,
歸納如下:
Swift
統(tǒng)一的函數(shù)語法足夠靈活,可以用來表示任何函數(shù),包括從最簡單的沒有參數(shù)名字的 C 風(fēng)格函數(shù),到復(fù)雜的帶局部和外部參數(shù)名的 Objective-C
風(fēng)格函數(shù)。參數(shù)可以提供默認(rèn)值荠瘪,以簡化函數(shù)調(diào)用。參數(shù)也可以既當(dāng)做傳入?yún)?shù)赛惩,也當(dāng)做傳出參數(shù)哀墓,也就是說,一旦函數(shù)執(zhí)行結(jié)束喷兼,傳入的參數(shù)值可以被修改篮绰。
這里面說了下面四種函數(shù),我來分別舉例:
1.沒有參數(shù)名字的C風(fēng)格函數(shù)
func sayHelloWorld() -> String {
return "hello,world"
}
print(sayHelloWorld())
// prints "hello, world"
2.帶局部和外部參數(shù)名的Obj-C風(fēng)格函數(shù)
如果你提供了外部參數(shù)名季惯,那么函數(shù)在被調(diào)用時吠各,必須使用外部參數(shù)名。
func someFunction(externalParameterName localParameterName: Int) {
// function body goes here, and can use localParameterName
// to refer to the argument value for that parameter
}
func sayHello(to person: String, and anotherPerson: String) -> String {
return "Hello \(person) and \(anotherPerson)!"
}
print(sayHello(to: "Bill", and: "Ted"))
// prints "Hello Bill and Ted!"
3.提供默認(rèn)值的函數(shù)
將帶有默認(rèn)值的參數(shù)放在函數(shù)參數(shù)列表的最后勉抓。這樣可以保證在函數(shù)調(diào)用時贾漏,非默認(rèn)參數(shù)的順序是一致的,同時使得相同的函數(shù)在不同情況下調(diào)用時顯得更為清晰藕筋。
func someFunction(parameterWithDefault: Int = 12) {
// function body goes here
// if no arguments are passed to the function call,
// value of parameterWithDefault is 12
}
someFunction(6) // parameterWithDefault is 6
someFunction() // parameterWithDefault is 12
4.參數(shù)既當(dāng)做傳入?yún)?shù)也做傳出參數(shù)的函數(shù)
輸入輸出參數(shù)和返回值是不一樣的纵散。上面的 swapTwoInts 函數(shù)并沒有定義任何返回值,但仍然修改了 someInt和 anotherInt 的值。輸入輸出參數(shù)是函數(shù)對函數(shù)體外產(chǎn)生影響的另一種方式困食。
func swapTwoInts(inout a: Int, inout _ b: Int) {
let temporaryA = a
a = b
b = temporaryA
}
在 Swift中,每個函數(shù)都有一種類型翎承,包括函數(shù)的參數(shù)值類型和返回值類型硕盹。
你可以把函數(shù)類型當(dāng)做任何其他普通變量類型一樣處理,這樣就可以更簡單地把函數(shù)當(dāng)做別的函數(shù)的參數(shù)叨咖,也可以從其他函數(shù)中返回函數(shù)瘩例。
函數(shù)的定義可以寫在其他函數(shù)定義中,這樣可以在嵌套函數(shù)范圍內(nèi)實現(xiàn)功能封裝甸各。
5.用另一個函數(shù)來當(dāng)做參數(shù)的函數(shù)
func addTwoInts(a: Int, _ b: Int) -> Int {
return a + b
}
var mathFunction: (Int, Int) -> Int = addTwoInts
func printMathResult(mathFunction: (Int, Int) -> Int, _ a: Int, _ b: Int) {
print("Result: \(mathFunction(a, b))")
}
printMathResult(addTwoInts, 3, 5)
// prints "Result: 8"
6.從其他函數(shù)中返回函數(shù)的函數(shù)
func stepForward(input: Int) -> Int {
return input + 1
}
func stepBackward(input: Int) -> Int {
return input - 1
}
func chooseStepFunction(backwards: Bool) ->(Int) -> Int {
return backwards ? stepBackward : stepForward
}
var currentValue = 3
let moveNearerToZero = chooseStepFunction(currentValue > 0)
// moveNearerToZero now refers to the stepBackward() function
print("Counting to zero:")
// Counting to zero:
while currentValue != 0 {
print("\(currentValue)...")
currentValue = moveNearerToZero(currentValue)
}
print("zero!")
// 3...
// 2...
// 1...
// zero!
7.定義寫在其他函數(shù)定義中的函數(shù)---嵌套函數(shù)
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)
// moveNearerToZero now refers to the nested stepForward() function
while currentValue != 0 {
print("\(currentValue)...")
currentValue = moveNearerToZero(currentValue)
}
print("zero!")
// -4...
// -3...
// -2...
// -1...
// zero!
補充:
8.多參數(shù)函數(shù)
func sayHello(personName: String, alreadyGreeted:Bool) -> String {
if alreadyGreeted {
return sayHelloAgain(personName)
} else {
return sayHello(personName)
}
}
print(sayHello("Tim", alreadyGreeted: true))
// prints "Hello again, Tim!"
9.無返回值函數(shù)
func sayHello(personName: String, alreadyGreeted: Bool) -> String {
if alreadyGreeted {
return sayHelloAgain(personName)
} else {
return sayHello(personName)
}
}
print(sayHello("Tim", alreadyGreeted: true))
// prints "Hello again, Tim!"
10.多重返回值函數(shù)
func minMax(array: [Int]) -> (min: Int, max: Int) {
var currentMin = array[0]
var currentMax = array[0]
for value in array[1..<array.count] {
if value < currentMin {
currentMin = value
} else if value > currentMax {
currentMax = value
}
}
return (currentMin, currentMax)
}
11.忽略外部參數(shù)名的函數(shù)
如果你不想為第二個及后續(xù)的參數(shù)設(shè)置外部參數(shù)名垛贤,用一個下劃線(_)代替一個明確的參數(shù)名。
func someFunction(firstParameterName: Int, _ secondParameterName: Int) {
// function body goes here
// firstParameterName and secondParameterName refer to
// the argument values for the first and second parameters
}
someFunction(1, 2)
12.擁有一個可變參數(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.25, 18.75)
// returns 10.0, which is the arithmetic mean of these three numbers
13.擁有變量參數(shù)的函數(shù)
對變量參數(shù)所進(jìn)行的修改在函數(shù)調(diào)用結(jié)束后便消失了聘惦,并且對于函數(shù)體外是不可見的。變量參數(shù)僅僅存在于函數(shù)調(diào)用的生命周期中儒恋。
func alignRight(var string: String, totalLength: Int, pad: Character) -> String {
let amountToPad = totalLength - string.characters.count
if amountToPad < 1 {
return string
}
let padString = String(pad)
for _ in 1...amountToPad {
string = padString + \string
}
return string
}
let originalString = "hello"
let paddedString = alignRight(originalString, totalLength: 10, pad:"-")
// paddedString is equal to "-----hello"
// originalString is still equal to "hello"