Swift4.0 函数(Function)

针对swift4.0函数做一些笔记。

  • 普通函数,不做过多笔记

func minMax(array: [Int]) -> (min: Int, max: Int) {
    var currentMin = array[0]
    var currentMax = array[0]
    for value in array[1.. currentMax {
            currentMax = value
        }
    }
    return (currentMin, currentMax)
}
  • 可变参数函数 (Variadic Parameters)

func arithmeticMean(numbers: Double...) -> Double {
    var total: Double = 0
    for number in numbers {
        total += number
    }
    return total / Double(numbers.count)
}
arithmeticMean(numbers: 1.0, 2.0, 3.0, 4.0, 5.0)
// result is 3.0
  • 输入输出参数函数(In-Out Parameters)

func swapTwoInts(a: inout Int, b: inout Int) {
    let temporaryA = a
    a = b
    b = temporaryA
}

var a = 10
var b = 20
swapTwoInts(a: &a, b: &b)
a    // 20
b    // 10
  • 函数类型(Function Types)

属性

func addTwoInts(_ a: Int, _ b: Int) -> Int {
    return a + b
}
var mathFunction: (Int, Int) -> Int =  addTwoInts   // addTwoInts(_:_:)
mathFunction(2,3)    // 5

函数作为参数(Function Types as Parameter Types)

func mathResult(_ mathFunction: (Int, Int) -> Int, _ a: Int, _ b: Int) {
    print("result = \(3 * mathFunction(a, b))")
}
mathResult(mathFunction, 2, 3)   // result = 15

函数作为返回值(Function Types as Return Types)

func stepForwrad(_ input: Int) -> Int {
    return input + 1
}

func stepBackward(_ input: Int) -> Int {
    return input - 1
}

func chooseSetpFunction(backward: Bool) -> (Int) -> Int {
    return backward ? stepForwrad : stepBackward
}

let moveNearerToZero = chooseSetpFunction(backward: false)
moveNearerToZero(3)    // 2

let moveFasterToZero = chooseSetpFunction(backward: true)
moveFasterToZero(4)    // 5
  • 嵌套函数(Nested Functions)

func chooseStepFunction(backward: Bool) -> (Int) -> Int {
    func stepForward(input: Int) -> Int { return input + 1 }
    func stepBackward(input: Int) -> Int { return input - 1 }
    return backward ? stepForward : stepBackward
}

var currentValue = 4
let moveNearToZero = chooseStepFunction(backward: false)
while currentValue != 0 {
    print("\(currentValue)...")
    currentValue = moveNearToZero(currentValue)
}
// 4...
// 3...
// 2...
// 1...

你可能感兴趣的:(Swift4.0 函数(Function))