函数

作者: 哈啰于先生 | 来源:发表于2019-08-26 10:26 被阅读0次

    函数 是执行一个具体任务的一段独立代码块

    函数的定义
    //无参函数
    func sayHelloWorld() -> String {
        return "hello, world"
    }
    //无返回值函数
    func greet(person: String) {
        print("Hello, \(person)!")
    }
    //有参数
    func greet(person: String) -> String {
        let greeting = "Hello, " + person + "!"
        return greeting
    }
    //多返回值
    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)
    }
    
    函数的参数标签和参数名
    //明确参数标签
    func greet(person: String, from hometown: String) -> String {
        return "Hello \(person)!  Glad you could visit from \(hometown)."
    }
    print(greet(person: "Bill", from: "Cupertino"))
    //参数标签省略
    func someFunction(_ firstParameterName: Int, secondParameterName: Int) {
        // 在函数体中,变量 firstParameterName 和 secondParameterName 分别对应第一个和第二个参数的值
    }
    someFunction(1, secondParameterName: 2)
    //参数默认值
    func someFunction(parameterWithoutDefault: Int, parameterWithDefault: Int = 12) {
        // 调用时如果你没有给第二个参数传值,那么变量  parameterWithDefault 的值默认就是 12 。
    }
    someFunction(parameterWithoutDefault: 3, parameterWithDefault: 6) // 变量 parameterWithDefault 的值是 6
    someFunction(parameterWithoutDefault: 4) // 变量 parameterWithDefault 的值是 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,5 个数的平均值是 3
    arithmeticMean(3, 8.25, 18.75)
    // returns 10.0,3 个数的平均值是 10.0
    
    函数类型

    每个函数都有种特定的函数类型,函数的类型由函数的参数类型和返回类型组成。

    这两个函数的类型是 (Int, Int) -> Int,可以解读为“这个函数类型有两个 Int 型的 参数并返回一个 Int 型的值。
     func addTwoInts(a: Int, _ b: Int) -> Int {
          return a + b
    }
    func multiplyTwoInts(a: Int, _ b: Int) -> Int {
         return a * b
    }
    //下面是另一个例子,一个没有参数,也没有返回值的函数:
    func printHelloWorld() {
        print("hello, world")
    }
    

    使用函数类型
    在 Swift 中,使用函数类型就像使用其他类型一样。例如,你可以定义一个类型为函数的常量或变量,并将适当的函数赋值给它:

        var mathFunction: (Int, Int) -> Int = addTwoInts
        //有相同匹配类型的不同函数可以被赋值给同一个变量,就像非函数类型的变量一样:
        mathFunction = multiplyTwoInts
        print("Result: \(mathFunction(2, 3))")
    

    函数类型作为参数类型
    可以将这种类型作为参数类型 (Int,Int)->Int

        func printMathResult(_ mathFunction: (Int, Int) -> Int, _ a: Int, _ b: Int) {
            print("Result: \(mathFunction(a, b))")
        }
        printMathResult(addTwoInts, 3, 5)
    

    函数类型作为返回类型
    你可以用函数类型作为另一个函数的返回类型。你需要做的是在返回箭头(->)后写一个完整的函数类型。

        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)
        
        while currentValue != 0 {
            currentValue = moveNearerToZero(currentValue)
            print("\(currentValue)... ")
        }
    

    嵌套函数(nested functions) 把函数定义在别的函数体中
    全局函数(global functions),它们定义在全局域中。
    默认情况下,嵌套函数是对外界不可见的,但是可以被它们的外围函数(enclosing function)调用。一个外围函数也可以返回它的某一个嵌套函数,使得这个函数可以在其他域中被使用。

        func chooseStepFunction2(backward: Bool) -> (Int) -> Int {
            func stepForward(input: Int) -> Int { return input + 1 }
            func stepBackward(input: Int) -> Int { return input - 1 }
            return backward ? stepBackward : stepForward
        }
        var anotherValue = -4
        let moveNearerToZero2 = chooseStepFunction2(backward: anotherValue > 0)
        while anotherValue != 0 {
            print("\(anotherValue)... ")
            anotherValue = moveNearerToZero2(anotherValue)
        }
    

    相关文章

      网友评论

          本文标题:函数

          本文链接:https://www.haomeiwen.com/subject/puxrectx.html