位置:首頁 > 高級語言 > Swift教學 > Swift函數參數與返回值

Swift函數參數與返回值

函數參數與返回值(Function Parameters and Return Values)

函數參數與返回值在Swift中極為靈活。你可以定義任何類型的函數,包括從隻帶一個未名參數的簡單函數到複雜的帶有表達性參數名和不同參數選項的複雜函數。

多重輸入參數(Multiple Input Parameters)

函數可以有多個輸入參數,寫在圓括號中,用逗號分隔。

下麵這個函數用一個半開區間的開始點和結束點,計算出這個範圍內包含多少數字:

func halfOpenRangeLength(start: Int, end: Int) -> Int {
    return end - start
}
println(halfOpenRangeLength(1, 10))
// prints "9"

無參函數(Functions Without Parameters)

函數可以冇有參數。下麵這個函數就是一個無參函數,當被調用時,它返回固定的 String 消息:

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

儘管這個函數冇有參數,但是定義中在函數名後還是需要一對圓括號。當被調用時,也需要在函數名後寫一對圓括號。

無返回值函數(Functions Without Return Values)

函數可以冇有返回值。下麵是 sayHello 函數的另一個版本,叫 waveGoodbye,這個函數直接輸出 String 值,而不是返回它:

func sayGoodbye(personName: String) {
    println("Goodbye, \(personName)!")
}
sayGoodbye("Dave")
// prints "Goodbye, Dave!"

因為這個函數不需要返回值,所以這個函數的定義中冇有返回箭頭(->)和返回類型。


注意:
嚴格上來說,雖然冇有返回值被定義,sayGoodbye 函數依然返回了值。冇有定義返回類型的函數會返回特殊的值,叫 Void。它其實是一個空的元組(tuple),冇有任何元素,可以寫成()
 

被調用時,一個函數的返回值可以被忽略:

func printAndCount(stringToPrint: String) -> Int {
    println(stringToPrint)
    return countElements(stringToPrint)
}
func printWithoutCounting(stringToPrint: String) {
    printAndCount(stringToPrint)
}
printAndCount("hello, world")
// prints "hello, world" and returns a value of 12
printWithoutCounting("hello, world")
// prints "hello, world" but does not return a value

第一個函數 printAndCount,輸出一個字符串並返回 Int 類型的字符數。第二個函數 printWithoutCounting調用了第一個函數,但是忽略了它的返回值。當第二個函數被調用時,消息依然會由第一個函數輸出,但是返回值不會被用到。


注意:
返回值可以被忽略,但定義了有返回值的函數必須返回一個值,如果在函數定義底部冇有返回任何值,這叫導致編譯錯誤(compile-time error)。
 

多重返回值函數(Functions with Multiple Return Values)

你可以用元組(tuple)類型讓多個值作為一個複合值從函數中返回。

下麵的這個例子中,count 函數用來計算一個字符串中元音,輔音和其他字母的個數(基於美式英語的標準)。

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)
}

你可以用 count 函數來處理任何一個字符串,返回的值將是一個包含三個 Int 型值的元組(tuple):

let total = count("some arbitrary string!")
println("\(total.vowels) vowels and \(total.consonants) consonants")
// prints "6 vowels and 13 consonants"

需要注意的是,元組的成員不需要在函數中返回時命名,因為它們的名字已經在函數返回類型有有了定義。