Swift4-函数

作者: wingsrao | 来源:发表于2018-08-09 10:55 被阅读7次

1.函数是一个独立的代码块,用来执行特定的任务。
2.定义

func greet(person: String) -> String {
    let greeting = "Hello, " + person + "!"
    return greeting
}
greet(person: "Anna")

3.没有定义返回类型的函数实际上会返回一个特殊的类型 Void,它其实是一个空的元组,作用相当于没有元素的元组,可以写作 ()
4.可选元组返回类型:例如 (Int, Int)? 或者 (String, Int, Bool)?
类似 (Int, Int)?的可选元组类型和包含可选类型的元组 (Int?, Int?)是不同的。对于可选元组类型,整个元组是可选的,而不仅仅是元组里边的单个值。
5.默认形式参数值

func someFunction(parameterWithDefault: Int = 12) {
    // In the function body, if no arguments are passed to the function
    // call, the value of parameterWithDefault is 12.
}
someFunction(parameterWithDefault: 6) // parameterWithDefault is 6
someFunction() 

6.一个函数最多只能有一个可变形式参数。

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)

7.输入输出形式参数不能有默认值,可变形式参数不能标记为 inout,如果你给一个形式参数标记了 inout,那么它们也不能标记 var和 let了。

func swapTwoInts(_ a: inout Int, _ b: inout Int) {
    let temporaryA = a
    a = b
    b = temporaryA
}
var someInt = 3
var anotherInt = 107
swapTwoInts(&someInt, &anotherInt)
//输入输出形式参数是函数能影响到函数范围外的另一种替代方式。

8.使用函数类型

func printHelloWorld() {
    print("hello, world")
}
//这个函数的类型是 () -> Void,或者 “一个没有形式参数的函数,返回 Void。”
func addTwoInts(_ a: Int, _ b: Int) -> Int {
    return a + b
}
var mathFunction: (Int, Int) -> Int = addTwoInts

print("Result: \(mathFunction(2, 3))")

9.函数类型作为形式参数类型

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

10.函数类型作为返回类型
11.内嵌函数

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
}

相关文章

网友评论

    本文标题:Swift4-函数

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