Swift5 5.函数Function

Function

Function

只用return一行编写的任何函数都可以省略return。

// 没有参数
func sayHelloWorld() -> String {
    return "hello, world"
}

// 多个参数
func greet(person: String, alreadyGreeted: Bool) -> String {
    if alreadyGreeted {
        return greetAgain(person: person)
    } else {
        return greet(person: person)
    }
}

// 没有返回值
func greet(person: String) {
    print("Hello, \(person)!")
}
func printAndCount(string: String) -> Int {
    print(string)
    return string.count
}
func printWithoutCounting(string: String) {
    let _ = printAndCount(string: string)
}
printAndCount(string: "hello, world")
// prints "hello, world" and returns a value of 12
printWithoutCounting(string: "hello, world")
// prints "hello, world" but does not return a value

第一个函数printAndCount(string:)打印一个字符串,然后将其字符计数返回为Int。第二个函数printWithoutCounting(string:)调用第一个函数,但忽略其返回值。当调用第二个函数时,第一个函数仍会打印该消息,但是不使用返回的值。

具有多个返回值的函数

可以使用元组类型作为函数的返回类型,以将多个值作为一个复合返回值的一部分返回。

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)")
// Prints "min is -6 and max is 109"

在从函数返回元组时不必命名元组的成员,因为它们的名称已作为函数返回类型的一部分指定。

返回Optional

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

if let bounds = minMax(array: [8, -6, 2, 109, 3, 71]) {
    print("min is \(bounds.min) and max is \(bounds.max)")
}
// Prints "min is -6 and max is 109"

内部外部名称: Argument Labels and Parameter Names

// 指定参数标签
func someFunction(argumentLabel parameterName: Int) {
    // In the function body, parameterName refers to the argument value
    // for that parameter.
}

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

// 内外部名称一致,省略参数标签
func someFunction(_ firstParameterName: Int, secondParameterName: Int) {
    // In the function body, firstParameterName and secondParameterName
    // refer to the argument values for the first and second parameters.
}
someFunction(1, secondParameterName: 2)

默认参数值

可以通过在参数的类型之后为该参数分配值来为函数中的任何参数定义默认值。如果定义了默认值,则可以在调用函数时忽略该参数。

func someFunction(parameterWithoutDefault: Int, parameterWithDefault: Int = 12) {
    // If you omit the second argument when calling this function, then
    // the value of parameterWithDefault is 12 inside the function body.
}
someFunction(parameterWithoutDefault: 3, parameterWithDefault: 6) // parameterWithDefault is 6
someFunction(parameterWithoutDefault: 4) // parameterWithDefault is 12

可变参数

一个函数最多可以具有一个可变参数。
通过…在参数的类型名称后插入三个句点字符(…)来编写可变参数。

下面的示例为任意长度的数字列表计算算术平均值(也称为average):

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.0, which is the arithmetic mean of these five numbers
arithmeticMean(3, 8.25, 18.75)
// returns 10.0, which is the arithmetic mean of these three numbers

In-Out 参数

函数参数默认为常量,如果希望函数修改参数的值,并且希望这些更改在函数调用结束后仍然存在,请将该参数定义为In-Out Parameters。

只能将变量作为输入输出参数的参数传递。您不能将常量或文字值作为参数传递,因为无法修改常量和文字。当您将一个与号(&)作为变量传入in-out参数时,将它放在变量名的前面,以指示该变量可以被函数修改。

输入输出参数不能具有默认值,并且可变参数不能标记为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)")
// Prints "someInt is now 107, and anotherInt is now 3"

Function Types

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

// () -> Void
func printHelloWorld() {
    print("hello, world")
}

使用Function Types

可以将常量或变量定义为函数类型,然后为该变量分配适当的函数:

var mathFunction: (Int, Int) -> Int = addTwoInts

“定义一个名为mathFunction的变量,其类型为一个具有两个Int值并返回Int值的函数。” 设置这个变量来表示函数addTwoInts。”

print("Result: \(mathFunction(2, 3))")  // Prints "Result: 5"

let anotherMathFunction = addTwoInts  // 类型推断
// anotherMathFunction is inferred to be of type (Int, Int) -> Int

Function Types作为另一个函数的参数类型

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

本示例定义了一个名为printMathResult(::_:)的函数,该函数具有三个参数。第一个参数名为mathFunction,类型为(Int, Int) -> Int。第二个和第三个参数分别名为a和b,并且均为type Int。

Function Types作为返回类型

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 now refers to the stepBackward() function

print("Counting to zero:")
// Counting to zero:
while currentValue != 0 {
    print("\(currentValue)... ")
    currentValue = moveNearerToZero(currentValue)
}
print("zero!")
// 3...
// 2...
// 1...
// zero!

嵌套函数

嵌套函数默认情况下对外界隐藏,但仍可以由其封闭函数调用和使用。封闭函数还可以返回其嵌套函数之一,以允许该嵌套函数在另一个作用域中使用。
可以重写chooseStepFunction(backward:)并返回嵌套函数:

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!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值