<<Swift巩固笔记>> 第6篇 函数

260 阅读3分钟

函数的定义和使用

函数是一段完成特定任务的独立代码片段

函数参数与返回值

无参数函数

函数类型 () -> String

func sayHi() -> String {
    return "Hello World!"
}
print(sayHi())

多参数函数

函数类型 (String) -> String

func greetAgain(person: String) -> String {
    return "Hello again, " + person + "!"
}

函数类型 (String, Bool) -> String

func greet(person: String, alreadyGreeted: Bool) -> String {
    if alreadyGreeted {
        return greetAgain(person: person)
    } else {
        return greet(person: person)
    }
}
print(greet(person: "James", alreadyGreeted: true))

无返回值函数

func greet(person: String) {
    print("Hello, \(person)!")
}

多返回值函数

func minMax(arr: [Int]) -> (min: Int, max: Int) {
    var currentMin = arr[0]
    var currentMax = arr[0]
    for value in arr {
        if value > currentMax {
            currentMax = value
        } else if value < currentMin {
            currentMin = value
        }
    }
    return (currentMin, currentMax)
}
let (min, max) = minMax(arr: [5, 3, 4, 8])
print("min is \(min), max is \(max)")

可选元组返回类型

可选元组类型 (Int, Int)? 和 元组中包含可选类型 (Int?, Int?)是不同的

func minMax(arr: [Int]) -> (min: Int, max: Int)? {
    if arr.isEmpty {
        return nil
    }
    var currentMin = arr[0]
    var currentMax = arr[0]
    for value in arr {
        if value > currentMax {
            currentMax = value
        } else if value < currentMin {
            currentMin = value
        }
    }
    return (currentMin, currentMax)
}

if let (aMin, aMax) = minMax(arr: []) {
    print("min is \(aMin), max is \(aMax)")
}

函数参数标签和参数名称

指定参数标签

func someFunc(parameterLabel parameterName: String) {
    // 在函数体内, 我们使用parameterName
}

忽略参数标签

我们可以使用 _ 来代替一个明确的参数标签

func someFunc(_ parameterName: String) {
    // 在函数体内, 我们使用parameterName
}

默认情况下, 函数参数名称用作标签名称

func greet(person: String, hometown: String) -> String {
    return "Hello, \(person)! Glad you could visit from \(hometown)."
}
print(greet(person: "dell", hometown: "Xian"))

username, from 就是标签名称, person, hometown 就是参数名称 标签名称用户调用函数时使用, 参数名称在函数的实现中使用

func greet(username person: String, from hometown: String) -> String {
    return "Hello, \(person)! Glad you could visit from \(hometown)."
}
print(greet(username: "ross", from: "London"))

默认参数值

可以给参数设置一个默认值, 这样在调用函数时, 可以忽略这个参数

func someFunc(parameterWithOutDefault: Int, parameterWithDefault: Int = 10) {
    print("parameterWithOutDefault is \(parameterWithOutDefault), parameterWithDefault is \(parameterWithDefault)")
}
someFunc(parameterWithOutDefault: 3, parameterWithDefault: 5)
someFunc(parameterWithOutDefault: 9)

可变参数

一个函数最多只能拥有一个可变参数

func arithmeticMean(numbers: Double...) -> Double {
    var total: Double = 0
    for value in numbers {
        total += value
    }
    return total / Double(numbers.count)
}
print(arithmeticMean(numbers: 1, 2, 3, 4))

输入输出参数

函数参数默认是常量, 如果想要一个函数w可以修改参数的值, 那么这个参数可以定义为输入输出参数 inout 关键字

  1. 输入输出参数不能传入常量或字面量
  2. 输入输出参数不能有默认值, 而且可变参数不能用inout标记
func swaptwoInts(a: inout Int, b: inout Int) {
    let t = a;
    a = b;
    b = t;
}
var x = 3, y = 5
swap(&x, &y)
print("x is \(x), y is \(y)")

函数类型

函数类型由函数的参数类型和函数的返回值类型组成 函数类型: (Int, Int) -> Int

func addTwoInts(a: Int, b: Int) -> Int {
    return a + b
}

func multiTwoInts(a: Int, b: Int) -> Int {
    return a * b
}

函数类型: () -> Void

func printHello() {
    print("Hello")
}

使用函数类型

函数类型跟其它的基本数据类型没有区别

var mathFunc: (Int, Int) -> Int = addTwoInts
print(mathFunc(3, 5))

mathFunc = multiTwoInts
print(mathFunc(3, 5))

可以推导出函数变量类型, 推导出anotherMathFunc的类型为 (Int, Int) -> Int

let anotherMathFunc = multiTwoInts

函数类型作为参数类型

func printResult(mathFunc: (Int, Int) -> Int, a: Int, b: Int) {
    print(mathFunc(a, b))
}
printResult(mathFunc: addTwoInts, a: 6, b: 8)
printResult(mathFunc: multiTwoInts, a: 6, b: 8)

函数类型作为返回类型

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

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

func chooseStepFunc(backward: Bool) -> (Int) -> Int {
    return backward ? stepBackward : stepForward
}

var currentValue = 3
let function = chooseStepFunc(backward: currentValue > 0)
print("counting to zero")
while currentValue != 0 {
    print("\(currentValue)...")
    currentValue = function(currentValue)
}
print("zero!")

函数嵌套

定义在函数体中的函数称为嵌套函数

func chooseStepFunc(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 currentValue = -3
let function = chooseStepFunc(backward: currentValue > 0)
print("counting to zero")
while currentValue != 0 {
    print("\(currentValue)...")
    currentValue = function(currentValue)
}
print("zero!")

三个月没看Swift了, 沉迷摸鱼无法自拔!