Swift-函數(shù)

重新閱讀了Swift中文文檔的函數(shù)章節(jié),
總結(jié)出以下文檔中提到的13種函數(shù),
歸納如下:

Swift
統(tǒng)一的函數(shù)語法足夠靈活,可以用來表示任何函數(shù),包括從最簡單的沒有參數(shù)名字的 C 風格函數(shù),到復雜的帶局部和外部參數(shù)名的 Objective-C
風格函數(shù)。參數(shù)可以提供默認值,以簡化函數(shù)調(diào)用。參數(shù)也可以既當做傳入?yún)?shù),也當做傳出參數(shù),也就是說,一旦函數(shù)執(zhí)行結(jié)束,傳入的參數(shù)值可以被修改。

這里面說了下面四種函數(shù),我來分別舉例:

 

1.沒有參數(shù)名字的C風格函數(shù)

func sayHelloWorld() -> String {
    return "hello,world"
}
print(sayHelloWorld())
// prints "hello, world"

 

2.帶局部和外部參數(shù)名的Obj-C風格函數(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.提供默認值的函數(shù)

將帶有默認值的參數(shù)放在函數(shù)參數(shù)列表的最后。這樣可以保證在函數(shù)調(diào)用時,非默認參數(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ù)既當做傳入?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ù)類型當做任何其他普通變量類型一樣處理,這樣就可以更簡單地把函數(shù)當做別的函數(shù)的參數(shù),也可以從其他函數(shù)中返回函數(shù)。
函數(shù)的定義可以寫在其他函數(shù)定義中,這樣可以在嵌套函數(shù)范圍內(nèi)實現(xiàn)功能封裝。

 
5.用另一個函數(shù)來當做參數(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ù)所進行的修改在函數(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"

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容