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
})
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,479评论 0 23
  • 春过无痕,夏过无迹,秋来无声,冬去无影。日历又翻完了一本。总觉得这日子过得太匆忙,仿佛这个春天的花还开在昨日,仿佛...
    楚楚楚菇凉阅读 1,293评论 0 1
  • 所需工具 腾讯云服务器(申请地址:云服务器CVM-腾讯云 学生优惠套餐-腾讯云) xshell(用于与服务器远程连...
    狸狸深深阅读 4,985评论 6 5
  • 狐族雪域前修炼圣地,长年积雪萦绕,山上一身着蓝衣女子盘膝而坐,蔚蓝长衫与雪白积雪混为一体。 蓝衣女子面前一把琴玹,...
    妍羽阅读 3,342评论 4 5
  • 我希望你越来越漂亮,自信,迷人 性格互补,方得始终 沉默是的爱远比口头的爱来的深沉 用你的热情融化我的冰冷吧 我不...
    骚里骚气小可爱阅读 1,287评论 0 0