Swift语法备忘录3-Functions and Closures

Functions and Closures 函数和闭包

/Use func to declare a function.
Call a function by following its name with a list of arguments in parentheses.
Use -> to separate the parameter names and types from the function’s return type.
/

func greet(person: String, day: String) -> String {
    return "Hello \(person), today is \(day)."
}
print(greet(person: "Bob", day: "Tuesday")) // Hello Bob, today is Tuesday.

返回实时日期【函数名称字同上,编译器并不会冲突或者报错】

func greet(person: String) -> String {
    let day = Date()
    return "Hello \(person), today is \(day)."
}
print(greet(person: "Bob")) // Hello Bob, today is 2018-01-06 09:18:09 +0000.

函数定义时, 如果你不想为第二个及后续的参数设置外部参数名, 用一个下划线(_)代替一个明确的参数名
/By default, functions use their parameter names as labels for their arguments. Write a custom argument label before the parameter name, or write _ to use no argument label./

func greet(_ person: String, on day: String) -> String {
    return "Hello \(person), today is \(day)."
}
print(greet("Join", on: "Wednesday"))

或者酱紫,但是调用的时候可读性不强

func greet(_ person: String,_ day: String) -> String {
    return "Hello \(person), today is \(day)."
}
print(greet("Jerry","Wednesday"))

巧妙访问数组元素,可以通过索引index,也可以通过名称【如下案例 : statistics.sum】

func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) {
    var min = scores[0]
    var max = scores[0]
    var sum = 0
    
    for score in scores {
        if score > max {
            max = score
        } else if score < min {
            min = score
        }
        sum += score
    }
    
    return (min, max, sum)
}
let statistics = calculateStatistics(scores: [5, 3, 100, 3, 9])
print(statistics.sum)
print(statistics.2)

函数嵌套函数【即在函数内声明函数】一般用于函数内部复杂的场景
/Functions can be nested. Nested functions have access to variables that were declared in the outer function. You can use nested functions to organize the code in a function that is long or complex./

func returnFifteen() -> Int {
    var y = 10
    func add() {
        y += 5
    }
    add()
    return y
}
returnFifteen()

函数作为函数的返回值
/Functions are a first-class type. This means that a function can return another function as its value./

func makeIncrementer() -> ((Int) -> Int) {
    func addOne(number: Int) -> Int {
        return 1 + number
    }
    return addOne
}
var increment = makeIncrementer()
print(increment) // (Function)
print(increment(7)) // 8

函数作为另一个函数的参数

func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool {
    for item in list {
        if condition(item) {
            return true
        }
    }
    return false
}
func lessThanTen(number: Int) -> Bool {
    return number < 10
}
var numbers = [20, 19, 7, 12]
hasAnyMatches(list: numbers, condition: lessThanTen)
闭包

/Functions are actually a special case of closures: blocks of code that can be called later. The code in a closure has access to things like variables and functions that were available in the scope where the closure was created, even if the closure is in a different scope when it is executed—you saw an example of this already with nested functions. You can write a closure without a name by surrounding code with braces ({}). Use in to separate the arguments and return type from the body./
// 总结一下就是:
// 1.函数也是闭包的一种形式,代码块可以延迟执行嘛
// 2.闭包卡伊访问外部的变量
// 3.形式就是这么简单 ({})

numbers.map({ (number: Int) -> Int in
    let result = 3 * number
    return result
})

你可能感兴趣的:(Swift语法备忘录3-Functions and Closures)