Swift 3.0中文版(3)函数和闭包

函数和闭包

Usefuncto 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来声明一个函数,使用名字和参数来调用函数。使用->来指定函数返回值的类型。

func greet(name: String, day: String) -> String {

return "Hello \(name), today is \(day)."

}

greet("Bob", day: "Tuesday")

EXPERIMENT

Remove thedayparameter. Add a parameter to include today’s lunch special in the greeting.

练习: 删除day参数,添加一个参数来表示今天吃了什么午饭。使用元组来让一个函数返回多个值。该元组的元素可以用名称或数字来表示。

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([5, 3, 100, 3, 9])

print(statistics.sum)

print(statistics.2)

Functions can also take a variable number of arguments, collecting them into an array.

函数可以带有可变个数的参数,这些参数在函数内表现为数组的形式:

func sumOf(numbers: Int...) -> Int {

var sum = 0

for number in numbers {

sum += number

}

return sum

}

sumOf()

sumOf(42, 597, 12)

EXPERIMENT

Write a function that calculates the average of its arguments.

练习: 写一个计算参数平均值的函数。

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

increment(7)

A function can take another function as one of its arguments.

函数也可以当做参数传入另一个函数。

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(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 ({}). Useinto

separate the arguments and return type from the body.

函数实际上是一种特殊的闭包:它是一段能之后被调取的代码。闭包中的代码能访问闭包所建作用域中能得到的变

量和函数,即使闭包是在一个不同的作用域被执行的 - 你已经在嵌套函数例子中所看到。你可以使用{}来创建

一个匿名闭包。使用in将参数和返回值类型声明与闭包函数体进行分离。

numbers.map({

(number: Int) -> Int in

let result = 3 * number

return result

})

EXPERIMENT

Rewrite the closure to return zero for all odd numbers.

练习: 重写闭包,对所有奇数返回0。

You have several options for writing closures more concisely. When a closure’s type is already known, such as

the callback for a delegate, you can omit the type of its parameters, its return type, or both. Single statement

closures implicitly return the value of their only statement.

有很多种创建更简洁的闭包的方法。如果一个闭包的类型已知,比如作为一个回调函数,你可以忽略参数的类型

和返回值。单个语句闭包会把它语句的值当做结果返回。

let mappedNumbers = numbers.map({ number in 3 * number })

print(mappedNumbers)

You can refer to parameters by number instead of by name—this approach is especially useful in very short

closures. A closure passed as the last argument to a function can appear immediately after the parentheses.

When a closure is the only argument to a function, you can omit the parentheses entirely.

你可以通过参数位置而不是参数名字来引用参数——这个方法在非常短的闭包中非常有用。当一个闭包作为最后

一个参数传给一个函数的时候,它可以直接跟在括号后面。当一个闭包是传给函数的唯一参数,你可以完全忽略

括号。

let sortedNumbers = numbers.sort { $0 > $1 }

print(sortedNumbers)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 以下翻译自Apple官方文档,结合自己的理解记录下来。翻译基于 swift 3.0.1 原文地址 Closure...
    艺术农阅读 1,703评论 0 3
  • 86.复合 Cases 共享相同代码块的多个switch 分支 分支可以合并, 写在分支后用逗号分开。如果任何模式...
    无沣阅读 1,543评论 1 5
  • 君惟明气息因此亦岔,同样扑倒在大桶边缘。翠姨匆匆赶入,瞧见两人这副情形,暗暗叫苦。伸手去探君海棠胸口,面色大变,“...
    十一鸾阅读 323评论 0 1
  • 十一月的北国就开始飘雪了,这一天,我走在学校的小路上,两边的树高高矗立,光秃秃的枝桠就像是冰冷的雕塑,似乎万年未动...
    最爱睡觉的鱼阅读 395评论 1 2
  • 你眼中的我是怎么样的我 现实中的我在不断剥落 也许你认为我已经颓纰狰狞 但是我却心急如焚地褪尽尘世残骸 努力展示真...
    撑篙人阅读 205评论 0 5

友情链接更多精彩内容