• Welcome to Swift (苹果官方Swift文档初译与注解三十五)---248~253页(第五章-- 函数 完)


    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!

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

  • 相关阅读:
    集合赋值及for循环删除符合条件的元素
    shiro系列12:rememberme(记住我)
    shiro系列11:缓存
    shiro系列10:会话管理
    shiro系列8:授权源码解析
    shiro系列7:拦截器
    shiro系列6:授权
    shiro系列5:Realm
    shiro系列4:认证源码解析
    shiro系列3:MD5盐值加密认证流程
  • 原文地址:https://www.cnblogs.com/caios/p/3855404.html
Copyright © 2020-2023  润新知