Welcome to Swift (蘋果官方Swift文檔初譯與註解三十五)---248~253頁(第五章-- 函數 完)

來源:互聯網
上載者:User

標籤:style   使用   strong   os   io   for   

Function Types as Return Types (函數類型作為傳回值類型)

  一個函數的類型可以作為另一個函數的傳回值類型.可以在一個函數的傳回值箭頭後面寫上一個完整的函數類型.

  例如:

  下面的例子定義了兩個簡單的函數,分別為stepForward 和 stepBackward.其中stepForward函數傳回值比它的輸入值多1,stepBackward函數傳回值比它輸入值少1.這兩個函數的  類型都是(Int) -> Int:

    func stepForward(input: Int) -> Int {

        return input + 1

    }

    func stepBackward(input: Int) -> Int {

        return input - 1

    }

  這裡有一個函數chooseStepFunction,它的傳回型別是一個函數類型(Int) -> Int.函數chooseStepFunction根據它的布爾類型的參數返回stepForward函數類型或者stepBackward函  數類型 :

    func chooseStepFunction(backwards: Bool) -> (Int) -> Int {

        return backwards ? stepBackward : stepForward

    }

  現在你可以使用chooseStepFunction獲得一個函數:

    var currentValue = 3

    let moveNearerToZero = chooseStepFunction(currentValue > 0)

    // moveNearerToZero now refers to the stepBackward() function

    moveNearerToZero將根據適當的函數來計算,一直到零:

    println("Counting to zero:")

    // Counting to zero:

    while currentValue != 0 {

        println("\(currentValue)... ")

        currentValue = moveNearerToZero(currentValue)

    }

    println("zero!")

    // 3...

    // 2...

    // 1...

    // zero!

Nested Functions (函數嵌套)

  你可以在一個函數體內定義另一個函數,這種情況叫做嵌套函數.

  預設情況下,嵌套的函數對外界是不知的.但可以通過封裝它的函數來調用它.封裝它的函數可以將它作為函數的傳回值返回,這樣可以允許嵌套的函數在其他範圍使用.

  代碼範例:

    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 {

        println("\(currentValue)... ")

        currentValue = moveNearerToZero(currentValue)

    }

    println("zero!")

    // -4...

    // -3...

    // -2...

    // -1...

    // zero!

/********************本章完......************************/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.