Swift基础篇 --- 06函数

1.函数的定义与调用

//定义
func 函数名(参数名: 参数类型, 参数名: 参数类型, ...) -> 返回类型 {
    ...
    return ...
}
//调用
函数名(参数名: 实参)

2.函数参数与返回值

2.1 无参数函数

func sayHelloWorld() -> String {
    return "hello, world"
}
print(sayHelloWorld())
// 打印“hello, world”

2.2 多参数函数

func greet(person: String, alreadyGreeted: Bool) -> String {
    if alreadyGreeted {
        return greetAgain(person: person)
    } else {
        return greet(person: person)
    }
}
print(greet(person: "Tim", alreadyGreeted: true))
// 打印“Hello again, Tim!”

2.3 无返回值函数

func printAndCount(string: String) -> Int {
    print(string)
    return string.count
}
func printWithoutCounting(string: String) {
    let _ = printAndCount(string: string)
}
printAndCount(string: "hello, world")
// 打印“hello, world”,并且返回值 12
printWithoutCounting(string: "hello, world")
// 打印“hello, world”,但是没有返回任何值

返回值可以被忽略,但定义了有返回值的函数必须返回一个值,如果在函数定义底部没有返回任何值,将导致编译时错误。

2.4 多重返回值函数

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)
}

let bounds = minMax(array: [8, -6, 2, 109, 3, 71])
print("min is \(bounds.min) and max is \(bounds.max)")
// 打印“min is -6 and max is 109”

2.5 可选元组返回类型

func minMax(array: [Int]) -> (min: Int, max: Int)? {
    if array.isEmpty { return nil }
    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)
}
//使用可选绑定来检查 minMax(array:) 函数返回的是一个存在的元组值还是 nil
if let bounds = minMax(array: [8, -6, 2, 109, 3, 71]) {
    print("min is \(bounds.min) and max is \(bounds.max)")
}
// 打印“min is -6 and max is 109”

2.6 隐式返回的函数

如果一个函数的整个函数体是一个单行表达式,这个函数可以隐式地返回这个表达式

func greeting(for person: String) -> String {
    "Hello, " + person + "!"
}
print(greeting(for: "Dave"))
// 打印 "Hello, Dave!"

func anotherGreeting(for person: String) -> String {
    return "Hello, " + person + "!"
}
print(anotherGreeting(for: "Dave"))
// 打印 "Hello, Dave!"

任何一个可以被写成一行 return 语句的函数都可以忽略 return

3.函数参数标签和参数名称

每个函数参数都有一个参数标签以及一个参数名称。参数标签在调用函数的时候使用;调用的时候需要将函数的参数标签写在对应的参数前面。参数名称在函数的实现中使用。默认情况下,函数参数使用参数名称来作为它们的参数标签。

func someFunction(firstParameterName: Int, secondParameterName: Int) {
    // 在函数体内,firstParameterName 和 secondParameterName 代表参数中的第一个和第二个参数值
}
someFunction(firstParameterName: 1, secondParameterName: 2)

3.1 指定参数标签

可以在参数名称前指定它的参数标签,中间以空格分隔

func someFunction(argumentLabel parameterName: Int) {
    // 在函数体内,parameterName 代表参数值
}
func greet(person: String, from hometown: String) -> String {
    return "Hello \(person)!  Glad you could visit from \(hometown)."
}
print(greet(person: "Bill", from: "Cupertino"))
// 打印“Hello Bill!  Glad you could visit from Cupertino.”

3.2 忽略参数标签

如果不希望为某个参数添加一个标签,可以使用一个下划线(_)来代替一个明确的参数标签。

func someFunction(_ firstParameterName: Int, secondParameterName: Int) {
     // 在函数体内,firstParameterName 和 secondParameterName 代表参数中的第一个和第二个参数值
}
someFunction(1, secondParameterName: 2)

3.3 默认参数值

func someFunction(parameterWithoutDefault: Int, parameterWithDefault: Int = 12) {
    // 如果你在调用时候不传第二个参数,parameterWithDefault 会值为 12 传入到函数体中。
}
someFunction(parameterWithoutDefault: 3, parameterWithDefault: 6) // parameterWithDefault = 6
someFunction(parameterWithoutDefault: 4) // parameterWithDefault = 12

将不带有默认值的参数放在函数参数列表的最前。一般来说,没有默认值的参数更加的重要,将不带默认值的参数放在最前保证在函数调用时,非默认参数的顺序是一致的,同时也使得相同的函数在不同情况下调用时显得更为清晰。

3.4 可变参数

一个可变参数(variadic parameter)可以接受零个或多个值,通过在变量类型名后面加入(...)的方式来定义可变参数,可变参数的传入值在函数体中变为此类型的一个数组。

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)
// 返回 3.0, 是这 5 个数的平均数。
arithmeticMean(3, 8.25, 18.75)
// 返回 10.0, 是这 3 个数的平均数。

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

3.5 输入输出参数

使用 inout 关键字定义 输入输出参数

func swapTwoInts(_ a: inout Int, _ b: inout Int) {
    let temporaryA = a
    a = b
    b = temporaryA
}
var someInt = 3
var anotherInt = 107
swapTwoInts(&someInt, &anotherInt)
print("someInt is now \(someInt), and anotherInt is now \(anotherInt)")
// 打印“someInt is now 107, and anotherInt is now 3”

注意:

  • 函数参数默认是常量,在函数体中不能被更改。如果要修改函数参数,则把参数定义为 输入输出参数
  • 输入输出参数值在函数中被修改,替换原来的值并传出函数
  • 只能传入变量,不能传入常量或者字面量
  • 在函数调用时,需要在参数名前加 &
  • 输入输出参数不能有默认值,而且可变参数不能用 inout 标记。

4.函数类型

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

func addTwoInts(_ a: Int, _ b: Int) -> Int {
    return a + b
}
func multiplyTwoInts(_ a: Int, _ b: Int) -> Int {
    return a * b
}
//这两个函数的类型是 (Int, Int) -> Int
//可以解读为:“这个函数类型有两个 Int 型的参数并返回一个 Int 型的值”

4.1 使用函数类型

  • 可以定义一个类型为函数的常量或变量,并将适当的函数赋值给它:

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

    mathFunction = multiplyTwoInts
    print("Result: \(mathFunction(2, 3))")
    // Prints "Result: 6"
    
  • 当赋值一个函数给常量或变量时,可以让 Swift 来推断其函数类型

    let anotherMathFunction = addTwoInts
    // anotherMathFunction 被推断为 (Int, Int) -> Int 类型
    

4.2 函数类型作为参数类型

可以用 (Int, Int) -> Int 这样的函数类型作为另一个函数的参数类型。这样你可以将函数的一部分实现留给函数的调用者来提供。

func printMathResult(_ mathFunction: (Int, Int) -> Int, _ a: Int, _ b: Int) {
    print("Result: \(mathFunction(a, b))")
}
printMathResult(addTwoInts, 3, 5)
// 打印“Result: 8”
printMathResult(addTwoInts(_:_:), 4, 6)
// 打印“Result: 10”

4.3 函数类型作为返回类型

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

func stepForward(_ input: Int) -> Int {
    return input + 1
}
func stepBackward(_ input: Int) -> Int {
    return input - 1
}
func chooseStepFunction(backward: Bool) -> (Int) -> Int {
    return backward ? stepBackward : stepForward
}
var currentValue = 3
let moveNearerToZero = chooseStepFunction(backward: currentValue > 0)
// moveNearerToZero 现在指向 stepBackward() 函数。
print("Counting to zero:")
// Counting to zero:
while currentValue != 0 {
    print("\(currentValue)... ")
    currentValue = moveNearerToZero(currentValue)
}
print("zero!")
// 3...
// 2...
// 1...
// zero!

5.嵌套函数

把函数定义在别的函数体中,称作 嵌套函数

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

func chooseStepFunction(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 = -4
let moveNearerToZero = chooseStepFunction(backward: currentValue > 0)
// moveNearerToZero now refers to the nested stepForward() function
while currentValue != 0 {
    print("\(currentValue)... ")
    currentValue = moveNearerToZero(currentValue)
}
print("zero!")
// -4...
// -3...
// -2...
// -1...
// zero!
本文作者:Rui
发布时间:2021-03-23, 20:28:43
原始链接:https://wrf8.github.io/posts/383577965.html
版权声明:转载请保留原文链接及作者。

×

喜欢就点赞,疼爱就打赏