Merge pull request #151 from IceskYsl/gh-pages
修改02_Lexical_Structure.md里的代码块标示
This commit is contained in:
@ -27,19 +27,23 @@ Swift 统一的函数语法足够灵活,可以用来表示任何函数,包
|
||||
|
||||
在下面例子中的函数叫做`"greetingForPerson"`,之所以叫这个名字是因为这个函数用一个人的名字当做输入,并返回给这个人的问候语。为了完成这个任务,你定义一个输入参数-一个叫做 `personName` 的 `String` 值,和一个包含给这个人问候语的 `String` 类型的返回值:
|
||||
|
||||
func sayHello(personName: String) -> String {
|
||||
let greeting = "Hello, " + personName + "!"
|
||||
return greeting
|
||||
}
|
||||
```swift
|
||||
func sayHello(personName: String) -> String {
|
||||
let greeting = "Hello, " + personName + "!"
|
||||
return greeting
|
||||
}
|
||||
```
|
||||
|
||||
所有的这些信息汇总起来成为函数的定义,并以 `func` 作为前缀。指定函数返回类型时,用返回箭头 `->`(一个连字符后跟一个右尖括号)后跟返回类型的名称的方式来表示。
|
||||
|
||||
该定义描述了函数做什么,它期望接收什么和执行结束时它返回的结果是什么。这样的定义使的函数可以在别的地方以一种清晰的方式被调用:
|
||||
|
||||
println(sayHello("Anna"))
|
||||
// prints "Hello, Anna!"
|
||||
println(sayHello("Brian"))
|
||||
// prints "Hello, Brian!
|
||||
```swift
|
||||
println(sayHello("Anna"))
|
||||
// prints "Hello, Anna!"
|
||||
println(sayHello("Brian"))
|
||||
// prints "Hello, Brian!
|
||||
```
|
||||
|
||||
调用 `sayHello` 函数时,在圆括号中传给它一个 `String` 类型的实参。因为这个函数返回一个 `String` 类型的值,`sayHello` 可以被包含在 `println` 的调用中,用来输出这个函数的返回值,正如上面所示。
|
||||
|
||||
@ -49,11 +53,14 @@ Swift 统一的函数语法足够灵活,可以用来表示任何函数,包
|
||||
|
||||
为了简化这个函数的定义,可以将问候消息的创建和返回写成一句:
|
||||
|
||||
func sayHelloAgain(personName: String) -> String {
|
||||
return "Hello again, " + personName + "!"
|
||||
}
|
||||
println(sayHelloAgain("Anna"))
|
||||
// prints "Hello again, Anna!
|
||||
```swift
|
||||
func sayHelloAgain(personName: String) -> String {
|
||||
return "Hello again, " + personName + "!"
|
||||
}
|
||||
println(sayHelloAgain("Anna"))
|
||||
// prints "Hello again, Anna!
|
||||
```
|
||||
|
||||
<a name="Function_Parameters_and_Return_Values"></a>
|
||||
## 函数参数与返回值(Function Parameters and Return Values)
|
||||
|
||||
@ -65,21 +72,24 @@ Swift 统一的函数语法足够灵活,可以用来表示任何函数,包
|
||||
|
||||
下面这个函数用一个半开区间的开始点和结束点,计算出这个范围内包含多少数字:
|
||||
|
||||
func halfOpenRangeLength(start: Int, end: Int) -> Int {
|
||||
return end - start
|
||||
}
|
||||
println(halfOpenRangeLength(1, 10))
|
||||
// prints "9
|
||||
|
||||
```swift
|
||||
func halfOpenRangeLength(start: Int, end: Int) -> Int {
|
||||
return end - start
|
||||
}
|
||||
println(halfOpenRangeLength(1, 10))
|
||||
// prints "9
|
||||
```
|
||||
### 无参函数(Functions Without Parameters)
|
||||
|
||||
函数可以没有参数。下面这个函数就是一个无参函数,当被调用时,它返回固定的 `String` 消息:
|
||||
|
||||
func sayHelloWorld() -> String {
|
||||
return "hello, world"
|
||||
}
|
||||
println(sayHelloWorld())
|
||||
// prints "hello, world
|
||||
```swift
|
||||
func sayHelloWorld() -> String {
|
||||
return "hello, world"
|
||||
}
|
||||
println(sayHelloWorld())
|
||||
// prints "hello, world
|
||||
```
|
||||
|
||||
尽管这个函数没有参数,但是定义中在函数名后还是需要一对圆括号。当被调用时,也需要在函数名后写一对圆括号。
|
||||
|
||||
@ -87,11 +97,13 @@ Swift 统一的函数语法足够灵活,可以用来表示任何函数,包
|
||||
|
||||
函数可以没有返回值。下面是 `sayHello` 函数的另一个版本,叫 `waveGoodbye`,这个函数直接输出 `String` 值,而不是返回它:
|
||||
|
||||
func sayGoodbye(personName: String) {
|
||||
println("Goodbye, \(personName)!")
|
||||
}
|
||||
sayGoodbye("Dave")
|
||||
// prints "Goodbye, Dave!
|
||||
```swift
|
||||
func sayGoodbye(personName: String) {
|
||||
println("Goodbye, \(personName)!")
|
||||
}
|
||||
sayGoodbye("Dave")
|
||||
// prints "Goodbye, Dave!
|
||||
```
|
||||
|
||||
因为这个函数不需要返回值,所以这个函数的定义中没有返回箭头(->)和返回类型。
|
||||
|
||||
@ -101,17 +113,20 @@ Swift 统一的函数语法足够灵活,可以用来表示任何函数,包
|
||||
|
||||
被调用时,一个函数的返回值可以被忽略:
|
||||
|
||||
func printAndCount(stringToPrint: String) -> Int {
|
||||
println(stringToPrint)
|
||||
return countElements(stringToPrint)
|
||||
}
|
||||
func printWithoutCounting(stringToPrint: String) {
|
||||
printAndCount(stringToPrint)
|
||||
}
|
||||
printAndCount("hello, world")
|
||||
// prints "hello, world" and returns a value of 12
|
||||
printWithoutCounting("hello, world")
|
||||
// prints "hello, world" but does not return a value
|
||||
```swift
|
||||
func printAndCount(stringToPrint: String) -> Int {
|
||||
println(stringToPrint)
|
||||
return countElements(stringToPrint)
|
||||
}
|
||||
func printWithoutCounting(stringToPrint: String) {
|
||||
printAndCount(stringToPrint)
|
||||
}
|
||||
printAndCount("hello, world")
|
||||
// prints "hello, world" and returns a value of 12
|
||||
printWithoutCounting("hello, world")
|
||||
// prints "hello, world" but does not return a value
|
||||
|
||||
```
|
||||
|
||||
第一个函数 `printAndCount`,输出一个字符串并返回 `Int` 类型的字符数。第二个函数 `printWithoutCounting`调用了第一个函数,但是忽略了它的返回值。当第二个函数被调用时,消息依然会由第一个函数输出,但是返回值不会被用到。
|
||||
|
||||
@ -125,21 +140,23 @@ Swift 统一的函数语法足够灵活,可以用来表示任何函数,包
|
||||
|
||||
下面的这个例子中,`count` 函数用来计算一个字符串中元音,辅音和其他字母的个数(基于美式英语的标准)。
|
||||
|
||||
func count(string: String) -> (vowels: Int, consonants: Int, others: Int) {
|
||||
var vowels = 0, consonants = 0, others = 0
|
||||
for character in string {
|
||||
switch String(character).lowercaseString {
|
||||
case "a", "e", "i", "o", "u":
|
||||
++vowels
|
||||
case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
|
||||
"n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
|
||||
++consonants
|
||||
default:
|
||||
++others
|
||||
}
|
||||
```swift
|
||||
func count(string: String) -> (vowels: Int, consonants: Int, others: Int) {
|
||||
var vowels = 0, consonants = 0, others = 0
|
||||
for character in string {
|
||||
switch String(character).lowercaseString {
|
||||
case "a", "e", "i", "o", "u":
|
||||
++vowels
|
||||
case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
|
||||
"n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
|
||||
++consonants
|
||||
default:
|
||||
++others
|
||||
}
|
||||
return (vowels, consonants, others)
|
||||
}
|
||||
return (vowels, consonants, others)
|
||||
}
|
||||
```
|
||||
|
||||
你可以用 `count` 函数来处理任何一个字符串,返回的值将是一个包含三个 `Int` 型值的元组(tuple):
|
||||
|
||||
@ -153,10 +170,12 @@ Swift 统一的函数语法足够灵活,可以用来表示任何函数,包
|
||||
|
||||
以上所有的函数都给它们的参数定义了`参数名(parameter name)`:
|
||||
|
||||
func someFunction(parameterName: Int) {
|
||||
// function body goes here, and can use parameterName
|
||||
// to refer to the argument value for that parameter
|
||||
}
|
||||
```swift
|
||||
func someFunction(parameterName: Int) {
|
||||
// function body goes here, and can use parameterName
|
||||
// to refer to the argument value for that parameter
|
||||
}
|
||||
```
|
||||
|
||||
但是,这些参数名仅在函数体中使用,不能在函数调用时使用。这种类型的参数名被称作`局部参数名(local parameter name)`,因为它们只能在函数体中使用。
|
||||
|
||||
@ -166,10 +185,12 @@ Swift 统一的函数语法足够灵活,可以用来表示任何函数,包
|
||||
|
||||
如果你希望函数的使用者在调用函数时提供参数名字,那就需要给每个参数除了局部参数名外再定义一个`外部参数名`。外部参数名写在局部参数名之前,用空格分隔。
|
||||
|
||||
func someFunction(externalParameterName localParameterName: Int) {
|
||||
// function body goes here, and can use localParameterName
|
||||
// to refer to the argument value for that parameter
|
||||
}
|
||||
```swift
|
||||
func someFunction(externalParameterName localParameterName: Int) {
|
||||
// function body goes here, and can use localParameterName
|
||||
// to refer to the argument value for that parameter
|
||||
}
|
||||
```
|
||||
|
||||
> 注意:
|
||||
>
|
||||
@ -177,27 +198,35 @@ Swift 统一的函数语法足够灵活,可以用来表示任何函数,包
|
||||
|
||||
以下是个例子,这个函数使用一个`结合者(joiner)`把两个字符串联在一起:
|
||||
|
||||
func join(s1: String, s2: String, joiner: String) -> String {
|
||||
return s1 + joiner + s2
|
||||
}
|
||||
```swift
|
||||
func join(s1: String, s2: String, joiner: String) -> String {
|
||||
return s1 + joiner + s2
|
||||
}
|
||||
```
|
||||
|
||||
当你调用这个函数时,这三个字符串的用途是不清楚的:
|
||||
|
||||
join("hello", "world", ", ")
|
||||
// returns "hello, world
|
||||
```swift
|
||||
join("hello", "world", ", ")
|
||||
// returns "hello, world
|
||||
```
|
||||
|
||||
为了让这些字符串的用途更为明显,我们为 `join` 函数添加外部参数名:
|
||||
|
||||
func join(string s1: String, toString s2: String, withJoiner joiner: String) -> String {
|
||||
return s1 + joiner + s2
|
||||
}
|
||||
```swift
|
||||
func join(string s1: String, toString s2: String, withJoiner joiner: String) -> String {
|
||||
return s1 + joiner + s2
|
||||
}
|
||||
```
|
||||
|
||||
在这个版本的 `join` 函数中,第一个参数有一个叫 `string` 的外部参数名和 `s1` 的局部参数名,第二个参数有一个叫 `toString` 的外部参数名和 `s2` 的局部参数名,第三个参数有一个叫 `withJoiner` 的外部参数名和 `joiner` 的局部参数名。
|
||||
|
||||
现在,你可以使用这些外部参数名以一种清晰地方式来调用函数了:
|
||||
|
||||
join(string: "hello", toString: "world", withJoiner: ", ")
|
||||
// returns "hello, world
|
||||
```swift
|
||||
join(string: "hello", toString: "world", withJoiner: ", ")
|
||||
// returns "hello, world
|
||||
```
|
||||
|
||||
使用外部参数名让第二个版本的 `join` 函数的调用更为有表现力,更为通顺,同时还保持了函数体是可读的和有明确意图的。
|
||||
|
||||
@ -211,20 +240,23 @@ Swift 统一的函数语法足够灵活,可以用来表示任何函数,包
|
||||
|
||||
下面这个例子定义了一个叫 `containsCharacter` 的函数,使用`井号(#)`的方式定义了外部参数名:
|
||||
|
||||
func containsCharacter(#string: String, #characterToFind: Character) -> Bool {
|
||||
for character in string {
|
||||
if character == characterToFind {
|
||||
return true
|
||||
}
|
||||
```swift
|
||||
func containsCharacter(#string: String, #characterToFind: Character) -> Bool {
|
||||
for character in string {
|
||||
if character == characterToFind {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
return false
|
||||
}
|
||||
```
|
||||
|
||||
这样定义参数名,使得函数体更为可读,清晰,同时也可以以一个不含糊的方式被调用:
|
||||
|
||||
let containsAVee = containsCharacter(string: "aardvark", characterToFind: "v")
|
||||
// containsAVee equals true, because "aardvark" contains a "v”
|
||||
|
||||
```swift
|
||||
let containsAVee = containsCharacter(string: "aardvark", characterToFind: "v")
|
||||
// containsAVee equals true, because "aardvark" contains a "v”
|
||||
```
|
||||
|
||||
### 默认参数值(Default Parameter Values)
|
||||
|
||||
@ -236,20 +268,25 @@ Swift 统一的函数语法足够灵活,可以用来表示任何函数,包
|
||||
|
||||
以下是另一个版本的`join`函数,其中`joiner`有了默认参数值:
|
||||
|
||||
func join(string s1: String, toString s2: String, withJoiner joiner: String = " ") -> String {
|
||||
return s1 + joiner + s2
|
||||
}
|
||||
```swift
|
||||
func join(string s1: String, toString s2: String, withJoiner joiner: String = " ") -> String {
|
||||
return s1 + joiner + s2
|
||||
}
|
||||
```
|
||||
|
||||
像第一个版本的 `join` 函数一样,如果 `joiner` 被赋值时,函数将使用这个字符串值来连接两个字符串:
|
||||
|
||||
join(string: "hello", toString: "world", withJoiner: "-")
|
||||
// returns "hello-world
|
||||
```swift
|
||||
join(string: "hello", toString: "world", withJoiner: "-")
|
||||
// returns "hello-world
|
||||
```
|
||||
|
||||
当这个函数被调用时,如果 `joiner` 的值没有被指定,函数会使用默认值(" "):
|
||||
|
||||
join(string: "hello", toString:"world")
|
||||
// returns "hello world"
|
||||
|
||||
```swift
|
||||
join(string: "hello", toString:"world")
|
||||
// returns "hello world"
|
||||
```
|
||||
### 默认值参数的外部参数名(External Names for Parameters with Default Values)
|
||||
|
||||
在大多数情况下,给带默认值的参数起一个外部参数名是很有用的。这样可以保证当函数被调用且带默认值的参数被提供值时,实参的意图是明显的。
|
||||
@ -258,14 +295,18 @@ Swift 统一的函数语法足够灵活,可以用来表示任何函数,包
|
||||
|
||||
下面是 `join` 函数的另一个版本,这个版本中并没有为它的参数提供外部参数名,但是 `joiner` 参数依然有外部参数名:
|
||||
|
||||
func join(s1: String, s2: String, joiner: String = " ") -> String {
|
||||
return s1 + joiner + s2
|
||||
}
|
||||
```swift
|
||||
func join(s1: String, s2: String, joiner: String = " ") -> String {
|
||||
return s1 + joiner + s2
|
||||
}
|
||||
```
|
||||
|
||||
在这个例子中,Swift 自动为 `joiner` 提供了外部参数名。因此,当函数调用时,外部参数名必须使用,这样使得参数的用途变得清晰。
|
||||
|
||||
join("hello", "world", joiner: "-")
|
||||
// returns "hello-world"
|
||||
```swift
|
||||
join("hello", "world", joiner: "-")
|
||||
// returns "hello-world"
|
||||
```
|
||||
|
||||
> 注意:
|
||||
>
|
||||
@ -279,17 +320,19 @@ Swift 统一的函数语法足够灵活,可以用来表示任何函数,包
|
||||
|
||||
下面的这个函数用来计算一组任意长度数字的算术平均数:
|
||||
|
||||
func arithmeticMean(numbers: Double...) -> Double {
|
||||
var total: Double = 0
|
||||
for number in numbers {
|
||||
total += number
|
||||
}
|
||||
return total / Double(numbers.count)
|
||||
```swift
|
||||
func arithmeticMean(numbers: Double...) -> Double {
|
||||
var total: Double = 0
|
||||
for number in numbers {
|
||||
total += number
|
||||
}
|
||||
arithmeticMean(1, 2, 3, 4, 5)
|
||||
// returns 3.0, which is the arithmetic mean of these five numbers
|
||||
arithmeticMean(3, 8, 19)
|
||||
// returns 10.0, which is the arithmetic mean of these three numbers
|
||||
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, 19)
|
||||
// returns 10.0, which is the arithmetic mean of these three numbers
|
||||
```
|
||||
|
||||
> 注意:
|
||||
>
|
||||
@ -305,17 +348,19 @@ Swift 统一的函数语法足够灵活,可以用来表示任何函数,包
|
||||
|
||||
通过在参数名前加关键字 `var` 来定义变量参数:
|
||||
|
||||
func alignRight(var string: String, count: Int, pad: Character) -> String {
|
||||
let amountToPad = count - countElements(string)
|
||||
for _ in 1...amountToPad {
|
||||
string = pad + string
|
||||
}
|
||||
return string
|
||||
```swift
|
||||
func alignRight(var string: String, count: Int, pad: Character) -> String {
|
||||
let amountToPad = count - countElements(string)
|
||||
for _ in 1...amountToPad {
|
||||
string = pad + string
|
||||
}
|
||||
let originalString = "hello"
|
||||
let paddedString = alignRight(originalString, 10, "-")
|
||||
// paddedString is equal to "-----hello"
|
||||
// originalString is still equal to "hello"
|
||||
return string
|
||||
}
|
||||
let originalString = "hello"
|
||||
let paddedString = alignRight(originalString, 10, "-")
|
||||
// paddedString is equal to "-----hello"
|
||||
// originalString is still equal to "hello"
|
||||
```
|
||||
|
||||
这个例子中定义了一个新的叫做 `alignRight` 的函数,用来右对齐输入的字符串到一个长的输出字符串中。左侧空余的地方用指定的填充字符填充。这个例子中,字符串`"hello"`被转换成了`"-----hello"`。
|
||||
|
||||
@ -341,21 +386,25 @@ Swift 统一的函数语法足够灵活,可以用来表示任何函数,包
|
||||
|
||||
下面是例子,`swapTwoInts` 函数,有两个分别叫做 `a` 和 `b` 的输出输出参数:
|
||||
|
||||
func swapTwoInts(inout a: Int, inout b: Int) {
|
||||
let temporaryA = a
|
||||
a = b
|
||||
b = temporaryA
|
||||
}
|
||||
```swift
|
||||
func swapTwoInts(inout a: Int, inout b: Int) {
|
||||
let temporaryA = a
|
||||
a = b
|
||||
b = temporaryA
|
||||
}
|
||||
```
|
||||
|
||||
这个 `swapTwoInts` 函数仅仅交换 `a` 与 `b` 的值。该函数先将 `a` 的值存到一个暂时常量 `temporaryA` 中,然后将 `b` 的值赋给 `a`,最后将 `temporaryA` 幅值给 `b`。
|
||||
|
||||
你可以用两个 `Int` 型的变量来调用 `swapTwoInts`。需要注意的是,`someInt` 和 `anotherInt` 在传入 `swapTwoInts` 函数前,都加了 `&` 的前缀:
|
||||
|
||||
var someInt = 3
|
||||
var anotherInt = 107
|
||||
swapTwoInts(&someInt, &anotherInt)
|
||||
println("someInt is now \(someInt), and anotherInt is now \(anotherInt)")
|
||||
// prints "someInt is now 107, and anotherInt is now 3”
|
||||
```swift
|
||||
var someInt = 3
|
||||
var anotherInt = 107
|
||||
swapTwoInts(&someInt, &anotherInt)
|
||||
println("someInt is now \(someInt), and anotherInt is now \(anotherInt)")
|
||||
// prints "someInt is now 107, and anotherInt is now 3”
|
||||
```
|
||||
|
||||
从上面这个例子中,我们可以看到 `someInt` 和 `anotherInt` 的原始值在 `swapTwoInts` 函数中被修改,尽管它们的定义在函数体外。
|
||||
|
||||
@ -369,12 +418,14 @@ Swift 统一的函数语法足够灵活,可以用来表示任何函数,包
|
||||
|
||||
例如:
|
||||
|
||||
func addTwoInts(a: Int, b: Int) -> Int {
|
||||
return a + b
|
||||
}
|
||||
func multiplyTwoInts(a: Int, b: Int) -> Int {
|
||||
return a * b
|
||||
}
|
||||
```swift
|
||||
func addTwoInts(a: Int, b: Int) -> Int {
|
||||
return a + b
|
||||
}
|
||||
func multiplyTwoInts(a: Int, b: Int) -> Int {
|
||||
return a * b
|
||||
}
|
||||
```
|
||||
|
||||
这个例子中定义了两个简单的数学函数:`addTwoInts` 和 `multiplyTwoInts`。这两个函数都传入两个 `Int` 类型, 返回一个合适的`Int`值。
|
||||
|
||||
@ -382,9 +433,11 @@ Swift 统一的函数语法足够灵活,可以用来表示任何函数,包
|
||||
|
||||
下面是另一个例子,一个没有参数,也没有返回值的函数:
|
||||
|
||||
func printHelloWorld() {
|
||||
println("hello, world")
|
||||
}
|
||||
```swift
|
||||
func printHelloWorld() {
|
||||
println("hello, world")
|
||||
}
|
||||
```
|
||||
|
||||
这个函数的类型是:`() -> ()`,或者叫“没有参数,并返回 `Void` 类型的函数。”。没有指定返回类型的函数总返回 `Void`。在Swift中,`Void` 与空的元组是一样的。
|
||||
|
||||
@ -392,7 +445,9 @@ Swift 统一的函数语法足够灵活,可以用来表示任何函数,包
|
||||
|
||||
在Swift中,使用函数类型就像使用其他类型一样。例如,你可以定义一个类型为函数的常量或变量,并将函数赋值给它:
|
||||
|
||||
var mathFunction: (Int, Int) -> Int = addTwoInts
|
||||
```swift
|
||||
var mathFunction: (Int, Int) -> Int = addTwoInts
|
||||
```
|
||||
|
||||
这个可以读作:
|
||||
|
||||
@ -402,31 +457,38 @@ Swift 统一的函数语法足够灵活,可以用来表示任何函数,包
|
||||
|
||||
现在,你可以用 `mathFunction` 来调用被赋值的函数了:
|
||||
|
||||
println("Result: \(mathFunction(2, 3))")
|
||||
// prints "Result: 5
|
||||
```swift
|
||||
println("Result: \(mathFunction(2, 3))")
|
||||
// prints "Result: 5
|
||||
```
|
||||
|
||||
有相同匹配类型的不同函数可以被赋值给同一个变量,就像非函数类型的变量一样:
|
||||
|
||||
mathFunction = multiplyTwoInts
|
||||
println("Result: \(mathFunction(2, 3))")
|
||||
// prints "Result: 6"
|
||||
```swift
|
||||
mathFunction = multiplyTwoInts
|
||||
println("Result: \(mathFunction(2, 3))")
|
||||
// prints "Result: 6"
|
||||
```
|
||||
|
||||
就像其他类型一样,当赋值一个函数给常量或变量时,你可以让 Swift 来推测其函数类型:
|
||||
|
||||
let anotherMathFunction = addTwoInts
|
||||
// anotherMathFunction is inferred to be of type (Int, Int) -> Int
|
||||
|
||||
```swift
|
||||
let anotherMathFunction = addTwoInts
|
||||
// anotherMathFunction is inferred to be of type (Int, Int) -> Int
|
||||
```
|
||||
### 函数类型作为参数类型(Function Types as Parameter Types)
|
||||
|
||||
你可以用`(Int, Int) -> Int`这样的函数类型作为另一个函数的参数类型。这样你可以将函数的一部分实现交由给函数的调用者。
|
||||
|
||||
下面是另一个例子,正如上面的函数一样,同样是输出某种数学运算结果:
|
||||
|
||||
func printMathResult(mathFunction: (Int, Int) -> Int, a: Int, b: Int) {
|
||||
println("Result: \(mathFunction(a, b))")
|
||||
}
|
||||
printMathResult(addTwoInts, 3, 5)
|
||||
// prints "Result: 8”
|
||||
```swift
|
||||
func printMathResult(mathFunction: (Int, Int) -> Int, a: Int, b: Int) {
|
||||
println("Result: \(mathFunction(a, b))")
|
||||
}
|
||||
printMathResult(addTwoInts, 3, 5)
|
||||
// prints "Result: 8”
|
||||
```
|
||||
|
||||
这个例子定义了 `printMathResult` 函数,它有三个参数:第一个参数叫 `mathFunction`,类型是`(Int, Int) -> Int`,你可以传入任何这种类型的函数;第二个和第三个参数叫 `a` 和 `b`,它们的类型都是 `Int`,这两个值作为已给的函数的输入值。
|
||||
|
||||
@ -440,40 +502,49 @@ Swift 统一的函数语法足够灵活,可以用来表示任何函数,包
|
||||
|
||||
下面的这个例子中定义了两个简单函数,分别是 `stepForward` 和`stepBackward`。`stepForward` 函数返回一个比输入值大一的值。`stepBackward` 函数返回一个比输入值小一的值。这两个函数的类型都是 `(Int) -> Int`:
|
||||
|
||||
func stepForward(input: Int) -> Int {
|
||||
return input + 1
|
||||
}
|
||||
func stepBackward(input: Int) -> Int {
|
||||
return input - 1
|
||||
}
|
||||
```swift
|
||||
func stepForward(input: Int) -> Int {
|
||||
return input + 1
|
||||
}
|
||||
func stepBackward(input: Int) -> Int {
|
||||
return input - 1
|
||||
}
|
||||
```
|
||||
|
||||
下面这个叫做 `chooseStepFunction` 的函数,它的返回类型是 `(Int) -> Int` 的函数。`chooseStepFunction` 根据布尔值 `backwards` 来返回 `stepForward` 函数或 `stepBackward` 函数:
|
||||
|
||||
func chooseStepFunction(backwards: Bool) -> (Int) -> Int {
|
||||
return backwards ? stepBackward : stepForward
|
||||
}
|
||||
```swift
|
||||
func chooseStepFunction(backwards: Bool) -> (Int) -> Int {
|
||||
return backwards ? stepBackward : stepForward
|
||||
}
|
||||
```
|
||||
|
||||
你现在可以用 `chooseStepFunction` 来获得一个函数,不管是那个方向:
|
||||
|
||||
var currentValue = 3
|
||||
let moveNearerToZero = chooseStepFunction(currentValue > 0)
|
||||
// moveNearerToZero now refers to the stepBackward() function
|
||||
```swift
|
||||
var currentValue = 3
|
||||
let moveNearerToZero = chooseStepFunction(currentValue > 0)
|
||||
// moveNearerToZero now refers to the stepBackward() function
|
||||
```
|
||||
|
||||
上面这个例子中计算出从 `currentValue` 逐渐接近到`0`是需要向正数走还是向负数走。`currentValue` 的初始值是`3`,这意味着 `currentValue > 0` 是真的(`true`),这将使得 `chooseStepFunction` 返回 `stepBackward` 函数。一个指向返回的函数的引用保存在了 `moveNearerToZero` 常量中。
|
||||
|
||||
现在,`moveNearerToZero` 指向了正确的函数,它可以被用来数到`0`:
|
||||
|
||||
println("Counting to zero:")
|
||||
// Counting to zero:
|
||||
while currentValue != 0 {
|
||||
println("\(currentValue)... ")
|
||||
currentValue = moveNearerToZero(currentValue)
|
||||
}
|
||||
println("zero!")
|
||||
// 3...
|
||||
// 2...
|
||||
// 1...
|
||||
// zero!
|
||||
```swift
|
||||
println("Counting to zero:")
|
||||
// Counting to zero:
|
||||
while currentValue != 0 {
|
||||
println("\(currentValue)... ")
|
||||
currentValue = moveNearerToZero(currentValue)
|
||||
}
|
||||
println("zero!")
|
||||
// 3...
|
||||
// 2...
|
||||
// 1...
|
||||
// zero!
|
||||
```
|
||||
|
||||
<a name="Nested_Functions"></a>
|
||||
## 嵌套函数(Nested Functions)
|
||||
|
||||
@ -483,21 +554,23 @@ Swift 统一的函数语法足够灵活,可以用来表示任何函数,包
|
||||
|
||||
你可以用返回嵌套函数的方式重写 `chooseStepFunction` 函数:
|
||||
|
||||
func chooseStepFunction(backwards: Bool) -> (Int) -> Int {
|
||||
func stepForward(input: Int) -> Int { return input + 1 }
|
||||
func stepBackward(input: Int) -> Int { return input - 1 }
|
||||
return backwards ? stepBackward : stepForward
|
||||
}
|
||||
var currentValue = -4
|
||||
let moveNearerToZero = chooseStepFunction(currentValue > 0)
|
||||
// moveNearerToZero now refers to the nested stepForward() function
|
||||
while currentValue != 0 {
|
||||
println("\(currentValue)... ")
|
||||
currentValue = moveNearerToZero(currentValue)
|
||||
}
|
||||
println("zero!")
|
||||
// -4...
|
||||
// -3...
|
||||
// -2...
|
||||
// -1...
|
||||
// zero!
|
||||
```swift
|
||||
func chooseStepFunction(backwards: Bool) -> (Int) -> Int {
|
||||
func stepForward(input: Int) -> Int { return input + 1 }
|
||||
func stepBackward(input: Int) -> Int { return input - 1 }
|
||||
return backwards ? stepBackward : stepForward
|
||||
}
|
||||
var currentValue = -4
|
||||
let moveNearerToZero = chooseStepFunction(currentValue > 0)
|
||||
// moveNearerToZero now refers to the nested stepForward() function
|
||||
while currentValue != 0 {
|
||||
println("\(currentValue)... ")
|
||||
currentValue = moveNearerToZero(currentValue)
|
||||
}
|
||||
println("zero!")
|
||||
// -4...
|
||||
// -3...
|
||||
// -2...
|
||||
// -1...
|
||||
// zero!
|
||||
```
|
||||
@ -36,7 +36,7 @@ Swift支持如下所有C语言的位运算符:
|
||||
|
||||
这个运算符是前置的,所以请不加任何空格地写着操作数之前。
|
||||
|
||||
```
|
||||
```swift
|
||||
let initialBits: UInt8 = 0b00001111
|
||||
let invertedBits = ~initialBits // 等于 0b11110000
|
||||
```
|
||||
@ -53,7 +53,7 @@ let invertedBits = ~initialBits // 等于 0b11110000
|
||||
|
||||
以下代码,`firstSixBits`和`lastSixBits`中间4个位都为1。对它俩进行按位与运算后,就得到了`00111100`,即十进制的`60`。
|
||||
|
||||
```
|
||||
```swift
|
||||
let firstSixBits: UInt8 = 0b11111100
|
||||
let lastSixBits: UInt8 = 0b00111111
|
||||
let middleFourBits = firstSixBits & lastSixBits // 等于 00111100
|
||||
@ -67,7 +67,7 @@ let middleFourBits = firstSixBits & lastSixBits // 等于 00111100
|
||||
|
||||
如下代码,`someBits`和`moreBits`在不同位上有`1`。按位或运行的结果是`11111110`,即十进制的`254`。
|
||||
|
||||
```
|
||||
```swift
|
||||
let someBits: UInt8 = 0b10110010
|
||||
let moreBits: UInt8 = 0b01011110
|
||||
let combinedbits = someBits | moreBits // 等于 11111110
|
||||
@ -81,7 +81,7 @@ let combinedbits = someBits | moreBits // 等于 11111110
|
||||
|
||||
以下代码,`firstBits`和`otherBits`都有一个`1`跟另一个数不同的。所以按位异或的结果是把它这些位置为`1`,其他都置为`0`。
|
||||
|
||||
```
|
||||
```swift
|
||||
let firstBits: UInt8 = 0b00010100
|
||||
let otherBits: UInt8 = 0b00000101
|
||||
let outputBits = firstBits ^ otherBits // 等于 00010001
|
||||
@ -103,7 +103,7 @@ let outputBits = firstBits ^ otherBits // 等于 00010001
|
||||
|
||||

|
||||
|
||||
```
|
||||
```swift
|
||||
let shiftBits: UInt8 = 4 // 即二进制的00000100
|
||||
shiftBits << 1 // 00001000
|
||||
shiftBits << 2 // 00010000
|
||||
@ -114,7 +114,7 @@ shiftBits >> 2 // 00000001
|
||||
|
||||
你可以使用移位操作进行其他数据类型的编码和解码。
|
||||
|
||||
```
|
||||
```swift
|
||||
let pink: UInt32 = 0xCC6699
|
||||
let redComponent = (pink & 0xFF0000) >> 16 // redComponent 是 0xCC, 即 204
|
||||
let greenComponent = (pink & 0x00FF00) >> 8 // greenComponent 是 0x66, 即 102
|
||||
@ -176,7 +176,7 @@ let blueComponent = pink & 0x0000FF // blueComponent 是 0x99, 即 153
|
||||
|
||||
例如,`Int16`整型能承载的整数范围是`-32768`到`32767`,如果给它赋上超过这个范围的数,就会报错:
|
||||
|
||||
```
|
||||
```swift
|
||||
var potentialOverflow = Int16.max
|
||||
// potentialOverflow 等于 32767, 这是 Int16 能承载的最大整数
|
||||
potentialOverflow += 1
|
||||
@ -197,7 +197,7 @@ potentialOverflow += 1
|
||||
|
||||
下面例子使用了溢出加法`&+`来解剖的无符整数的上溢出
|
||||
|
||||
```
|
||||
```swift
|
||||
var willOverflow = UInt8.max
|
||||
// willOverflow 等于UInt8的最大整数 255
|
||||
willOverflow = willOverflow &+ 1
|
||||
@ -218,7 +218,7 @@ willOverflow = willOverflow &+ 1
|
||||
|
||||
Swift代码是这样的:
|
||||
|
||||
```
|
||||
```swift
|
||||
var willUnderflow = UInt8.min
|
||||
// willUnderflow 等于UInt8的最小值0
|
||||
willUnderflow = willUnderflow &- 1
|
||||
@ -231,7 +231,7 @@ willUnderflow = willUnderflow &- 1
|
||||
|
||||
来看看Swift代码:
|
||||
|
||||
```
|
||||
```swift
|
||||
var signedUnderflow = Int8.min
|
||||
// signedUnderflow 等于最小的有符整数 -128
|
||||
signedUnderflow = signedUnderflow &- 1
|
||||
@ -242,14 +242,14 @@ signedUnderflow = signedUnderflow &- 1
|
||||
|
||||
一个数除于0 `i / 0`,或者对0求余数 `i % 0`,就会产生一个错误。
|
||||
|
||||
```
|
||||
```swift
|
||||
let x = 1
|
||||
let y = x / 0
|
||||
```
|
||||
|
||||
使用它们对应的可溢出的版本的运算符`&/`和`&%`进行除0操作时就会得到`0`值。
|
||||
|
||||
```
|
||||
```swift
|
||||
let x = 1
|
||||
let y = x &/ 0
|
||||
// y 等于 0
|
||||
@ -264,7 +264,7 @@ let y = x &/ 0
|
||||
|
||||
在混合表达式中,运算符的优先级和结合性是非常重要的。举个例子,为什么下列表达式的结果为`4`?
|
||||
|
||||
```
|
||||
```swift
|
||||
2 + 3 * 4 % 5
|
||||
// 结果是 4
|
||||
```
|
||||
@ -282,7 +282,7 @@ let y = x &/ 0
|
||||
|
||||
乘法和求余拥有相同的优先级,在运算过程中,我们还需要结合性,乘法和求余运算都是左结合的。这相当于在表达式中有隐藏的括号让运算从左开始。
|
||||
|
||||
```
|
||||
```swift
|
||||
2 + ((3 * 4) % 5)
|
||||
```
|
||||
|
||||
@ -290,14 +290,14 @@ let y = x &/ 0
|
||||
3 * 4 = 12,所以这相当于:
|
||||
|
||||
|
||||
```
|
||||
```swift
|
||||
2 + (12 % 5)
|
||||
```
|
||||
|
||||
(12 % 5) is 2, so this is equivalent to:
|
||||
12 % 5 = 2,所这又相当于
|
||||
|
||||
```
|
||||
```swift
|
||||
2 + 2
|
||||
```
|
||||
|
||||
@ -318,7 +318,7 @@ Swift的运算符较C语言和Objective-C来得更简单和保守,这意味着
|
||||
|
||||
例子中定义了一个名为`Vector2D`的二维坐标向量 `(x,y)` 的结构,然后定义了让两个`Vector2D`的对象相加的运算符函数。
|
||||
|
||||
```
|
||||
```swift
|
||||
struct Vector2D {
|
||||
var x = 0.0, y = 0.0
|
||||
}
|
||||
@ -334,7 +334,7 @@ struct Vector2D {
|
||||
|
||||
这个函数是全局的,而不是`Vector2D`结构的成员方法,所以任意两个`Vector2D`对象都可以使用这个中置运算符。
|
||||
|
||||
```
|
||||
```swift
|
||||
let vector = Vector2D(x: 3.0, y: 1.0)
|
||||
let anotherVector = Vector2D(x: 2.0, y: 4.0)
|
||||
let combinedVector = vector + anotherVector
|
||||
@ -351,7 +351,7 @@ let combinedVector = vector + anotherVector
|
||||
|
||||
实现一个前置或后置运算符时,在定义该运算符的时候于关键字`func`之前标注 `@prefix` 或 `@postfix` 属性。
|
||||
|
||||
```
|
||||
```swift
|
||||
@prefix func - (vector: Vector2D) -> Vector2D {
|
||||
return Vector2D(x: -vector.x, y: -vector.y)
|
||||
}
|
||||
@ -361,7 +361,7 @@ let combinedVector = vector + anotherVector
|
||||
|
||||
对于数值,单目减运算符可以把正数变负数,把负数变正数。对于`Vector2D`,单目减运算将其`x`和`y`都进进行单目减运算。
|
||||
|
||||
```
|
||||
```swift
|
||||
let positive = Vector2D(x: 3.0, y: 4.0)
|
||||
let negative = -positive
|
||||
// negative 为 (-3.0, -4.0)
|
||||
@ -373,7 +373,7 @@ let alsoPositive = -negative
|
||||
|
||||
组合赋值是其他运算符和赋值运算符一起执行的运算。如`+=`把加运算和赋值运算组合成一个操作。实现一个组合赋值符号需要使用`@assignment`属性,还需要把运算符的左参数设置成`inout`,因为这个参数会在运算符函数内直接修改它的值。
|
||||
|
||||
```
|
||||
```swift
|
||||
@assignment func += (inout left: Vector2D, right: Vector2D) {
|
||||
left = left + right
|
||||
}
|
||||
@ -381,7 +381,7 @@ let alsoPositive = -negative
|
||||
|
||||
因为加法运算在之前定义过了,这里无需重新定义。所以,加赋运算符函数使用已经存在的高级加法运算符函数来执行左值加右值的运算。
|
||||
|
||||
```
|
||||
```swift
|
||||
var original = Vector2D(x: 1.0, y: 2.0)
|
||||
let vectorToAdd = Vector2D(x: 3.0, y: 4.0)
|
||||
original += vectorToAdd
|
||||
@ -390,7 +390,7 @@ original += vectorToAdd
|
||||
|
||||
你可以将 `@assignment` 属性和 `@prefix` 或 `@postfix` 属性起来组合,实现一个`Vector2D`的前置运算符。
|
||||
|
||||
```
|
||||
```swift
|
||||
@prefix @assignment func ++ (inout vector: Vector2D) -> Vector2D {
|
||||
vector += Vector2D(x: 1.0, y: 1.0)
|
||||
return vector
|
||||
@ -399,7 +399,7 @@ original += vectorToAdd
|
||||
|
||||
这个前置使用了已经定义好的高级加赋运算,将自己加上一个值为 `(1.0,1.0)` 的对象然后赋给自己,然后再将自己返回。
|
||||
|
||||
```
|
||||
```swift
|
||||
var toIncrement = Vector2D(x: 3.0, y: 4.0)
|
||||
let afterIncrement = ++toIncrement
|
||||
// toIncrement 现在是 (4.0, 5.0)
|
||||
@ -416,7 +416,7 @@ Swift无所知道自定义类型是否相等或不等,因为等于或者不等
|
||||
|
||||
定义相等运算符函数跟定义其他中置运算符雷同:
|
||||
|
||||
```
|
||||
```swift
|
||||
@infix func == (left: Vector2D, right: Vector2D) -> Bool {
|
||||
return (left.x == right.x) && (left.y == right.y)
|
||||
}
|
||||
@ -430,7 +430,7 @@ Swift无所知道自定义类型是否相等或不等,因为等于或者不等
|
||||
|
||||
现在我们可以使用这两个运算符来判断两个`Vector2D`对象是否相等。
|
||||
|
||||
```
|
||||
```swift
|
||||
let twoThree = Vector2D(x: 2.0, y: 3.0)
|
||||
let anotherTwoThree = Vector2D(x: 2.0, y: 3.0)
|
||||
if twoThree == anotherTwoThree {
|
||||
@ -445,14 +445,14 @@ if twoThree == anotherTwoThree {
|
||||
|
||||
新的运算符声明需在全局域使用`operator`关键字声明,可以声明为前置,中置或后置的。
|
||||
|
||||
```
|
||||
```swift
|
||||
operator prefix +++ {}
|
||||
```
|
||||
|
||||
|
||||
这段代码定义了一个新的前置运算符叫`+++`,此前Swift并不存在这个运算符。此处为了演示,我们让`+++`对`Vector2D`对象的操作定义为 `双自增` 这样一个独有的操作,这个操作使用了之前定义的加赋运算实现了自已加上自己然后返回的运算。
|
||||
|
||||
```
|
||||
```swift
|
||||
@prefix @assignment func +++ (inout vector: Vector2D) -> Vector2D {
|
||||
vector += vector
|
||||
return vector
|
||||
@ -461,7 +461,7 @@ operator prefix +++ {}
|
||||
|
||||
`Vector2D` 的 `+++` 的实现和 `++` 的实现很接近, 唯一不同的前者是加自己, 后者是加值为 `(1.0, 1.0)` 的向量.
|
||||
|
||||
```
|
||||
```swift
|
||||
var toBeDoubled = Vector2D(x: 1.0, y: 4.0)
|
||||
let afterDoubling = +++toBeDoubled
|
||||
// toBeDoubled 现在是 (2.0, 8.0)
|
||||
@ -478,7 +478,7 @@ let afterDoubling = +++toBeDoubled
|
||||
|
||||
以下例子定义了一个新的中置符`+-`,是左结合的`left`,优先级为`140`。
|
||||
|
||||
```
|
||||
```swift
|
||||
operator infix +- { associativity left precedence 140 }
|
||||
func +- (left: Vector2D, right: Vector2D) -> Vector2D {
|
||||
return Vector2D(x: left.x + right.x, y: left.y - right.y)
|
||||
|
||||
@ -101,9 +101,11 @@ Swift 的“词法结构(*lexical structure*)”描述了如何在该语言
|
||||
|
||||
字面值表示整型、浮点型数字或文本类型的值,举例如下:
|
||||
|
||||
42 // 整型字面量
|
||||
3.14159 // 浮点型字面量
|
||||
"Hello, world!" // 文本型字面量
|
||||
```swift
|
||||
42 // 整型字面量
|
||||
3.14159 // 浮点型字面量
|
||||
"Hello, world!" // 文本型字面量
|
||||
```
|
||||
|
||||
> 字面量语法
|
||||
>
|
||||
@ -119,8 +121,10 @@ Swift 的“词法结构(*lexical structure*)”描述了如何在该语言
|
||||
|
||||
允许使用下划线 `_` 来增加数字的可读性,下划线不会影响字面量的值。整型字面量也可以在数字前加 `0`,同样不会影响字面量的值。
|
||||
|
||||
1000_000 // 等于 1000000
|
||||
005 // 等于 5
|
||||
```swift
|
||||
1000_000 // 等于 1000000
|
||||
005 // 等于 5
|
||||
```
|
||||
|
||||
除非特殊指定,整型字面量的默认类型为 Swift 标准库类型中的 `Int`。Swift 标准库还定义了其他不同长度以及是否带符号的整数类型,请参考 [整数类型](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-XID_411)。
|
||||
|
||||
@ -182,8 +186,10 @@ Swift 的“词法结构(*lexical structure*)”描述了如何在该语言
|
||||
|
||||
允许使用下划线 `_` 来增强可读性,下划线不会影响字面量的值。浮点型字面量也可以在数字前加 `0`,同样不会影响字面量的值。
|
||||
|
||||
10_000.56 // 等于 10000.56
|
||||
005000.76 // 等于 5000.76
|
||||
```swift
|
||||
10_000.56 // 等于 10000.56
|
||||
005000.76 // 等于 5000.76
|
||||
```
|
||||
|
||||
除非特殊指定,浮点型字面量的默认类型为 Swift 标准库类型中的 `Double`,表示64位浮点数。Swift 标准库也定义 `Float` 类型,表示32位浮点数。
|
||||
|
||||
@ -239,10 +245,12 @@ Swift 的“词法结构(*lexical structure*)”描述了如何在该语言
|
||||
|
||||
例如,以下所有文本型字面量的值相同:
|
||||
|
||||
"1 2 3"
|
||||
"1 2 \(3)"
|
||||
"1 2 \(1 + 2)"
|
||||
var x = 3; "1 2 \(x)"
|
||||
```swift
|
||||
"1 2 3"
|
||||
"1 2 \(3)"
|
||||
"1 2 \(1 + 2)"
|
||||
var x = 3; "1 2 \(x)"
|
||||
```
|
||||
|
||||
文本型字面量的默认类型为 `String`。组成字符串的字符类型为 `Character`。更多有关 `String` 和 `Character` 的信息请参照 [字符串和字符](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/StringsAndCharacters.html#//apple_ref/doc/uid/TP40014097-CH7-XID_368)。
|
||||
|
||||
|
||||
Reference in New Issue
Block a user