<pre name="code" class="objc">import Foundation
/**
* 1.函數的定義與與調用
*/
func sayHello(personName: String) -> String {
let greeting = "Hello, " + personName + "!"
return greeting
}
print(sayHello("Anna"))
// prints "Hello, Anna!"
//------無參函數
func sayHelloWorld() -> String {
return "hello, world"
}
print(sayHelloWorld())
// prints "hello, world"
//------多參函數
func sayHello(personName: String, alreadyGreeted: Bool) -> String {
if alreadyGreeted {
return "Hello again " + personName;
} else {
return sayHello(personName)
}
}
print(sayHello("Tim", alreadyGreeted: true))
// prints "Hello again, Tim!"
//------無傳回值函數
func sayGoodbye(personName: String) {
print("Goodbye, \(personName)!")
}
sayGoodbye("Dave")
// prints "Goodbye, Dave!"
//------多重傳回值函數,傳回元組
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)
}
let bounds = minMax([8, -6, 2, 109, 3, 71])
print("min is \(bounds.min) and max is \(bounds.max)")
// prints "min is -6 and max is 109"
//------可選元組傳回類型
func minMax1(array: [Int]) -> (min: Int, max: Int)? {
if array.isEmpty { return nil }
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)
}
if let bounds = minMax1([8, -6, 2, 109, 3, 71]) {
print("min is \(bounds.min) and max is \(bounds.max)")
}
// prints "min is -6 and max is 109"
/**
* 2.函數參數名稱
函數參數都有一個外部參數名和一個局部參數名。外部參數名用于在函數調用時标注傳遞給函數的參數,局部參數名在函數的實作内部使用。
*/
func someFunction(firstParameterName: Int, secondParameterName: Int) {
//一般情況下,第一個參數省略其外部參數名,第二個以及随後的參數使用其局部參數名作為外部參數名。
}
someFunction(1, secondParameterName: 2)
//-----指定外部參數名
func someFunction1(externalParameterName localParameterName: Int) {
//如果你提供了外部參數名,那麼函數在被調用時,必須使用外部參數名。
}
func sayHello1(to person: String, and anotherPerson: String) -> String {
return "Hello \(person) and \(anotherPerson)!"
}
print(sayHello1(to: "Bill", and: "Ted"))
// prints "Hello Bill and Ted!"
//-----忽略外部參數名,用_代替
func someFunction2(firstParameterName: Int, _ secondParameterName: Int) {
// function body goes here
// firstParameterName and secondParameterName refer to
// the argument values for the first and second parameters
}
someFunction2(1, 2)
//-----預設參數值
func someFunction3(parameterWithDefault: Int = 12) {
//将帶有預設值的參數放在函數參數清單的最後。
}
someFunction3(6) // parameterWithDefault is 6
someFunction3() // parameterWithDefault is 12
//-----可變參數,通過在變量類型名後面加入(...)的方式來定義可變參數。
//一個函數最多隻能有一個可變參數。如果函數有一個或多個帶預設值的參數,而且還有一個可變參數,那麼把可變參數放在參數表的最後。
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
/**
* 3.輸入輸出參數
函數參數預設是常量。試圖在函數體中更改參數值将會導緻編譯錯誤。在參數加上inout
*/
func swapTwoInts(inout a: Int, inout _ b: 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)")
// prints "someInt is now 107, and anotherInt is now 3"
/**
* 4.函數類型
每個函數都有種特定的函數類型,由函數的參數類型和傳回類型組成。
*/
//這兩個函數的類型是 (Int, Int) -> Int
func addTwoInts(a: Int, _ b: Int) -> Int {
return a + b
}
func multiplyTwoInts(a: Int, _ b: Int) -> Int {
return a * b
}
//---------使用函數類型
//在 Swift 中,使用函數類型就像使用其他類型一樣。例如,你可以定義一個類型為函數的常量或變量,并将适當的函數指派給它
var mathFunction: (Int, Int) -> Int = addTwoInts
print("Result: \(mathFunction(2, 3))")
// prints "Result: 5"
mathFunction = multiplyTwoInts
print("Result: \(mathFunction(2, 3))")
// prints "Result: 6"
//---------函數類型作為參數類型
func printMathResult(mathFunction: (Int, Int) -> Int, _ a: Int, _ b: Int) {
print("Result: \(mathFunction(a, b))")
}
printMathResult(addTwoInts, 3, 5)
// prints "Result: 8"
//---------函數類型作為傳回類型
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!
/**
* 5.嵌套函數
之前見到的所有函數都叫全局函數,它們定義在全局域中。你也可以把函數定義在别的函數體中,稱作嵌套函數。
*/
func chooseStepFunction5(backwards: Bool) -> (Int) -> Int {
func stepForward5(input: Int) -> Int { return input + 1 }
func stepBackward5(input: Int) -> Int { return input - 1 }
return backwards ? stepBackward5 : stepForward5
}
var currentValue5 = -4
let moveNearerToZero5 = chooseStepFunction5(currentValue5 > 0)
// moveNearerToZero now refers to the nested stepForward() function
while currentValue5 != 0 {
print("\(currentValue5)... ")
currentValue5 = moveNearerToZero5(currentValue5)
}
print("zero!")
// -4...
// -3...
// -2...
// -1...
// zero!