替换println 为 print
This commit is contained in:
@ -121,28 +121,28 @@ languageName = "Swift++"
|
||||
|
||||
### 输出常量和变量
|
||||
|
||||
你可以用`println`函数来输出当前常量或变量的值:
|
||||
你可以用`print`函数来输出当前常量或变量的值:
|
||||
|
||||
```swift
|
||||
println(friendlyWelcome)
|
||||
print(friendlyWelcome)
|
||||
// 输出 "Bonjour!"
|
||||
```
|
||||
|
||||
`println`是一个用来输出的全局函数,输出的内容会在最后换行。如果你用 Xcode,`println`将会输出内容到“console”面板上。(另一种函数叫`print`,唯一区别是在输出内容最后不会换行。)
|
||||
`print`是一个用来输出的全局函数,输出的内容会在最后换行。如果你用 Xcode,`print`将会输出内容到“console”面板上。(另一种函数叫`print`,唯一区别是在输出内容最后不会换行。)
|
||||
|
||||
`println`函数输出传入的`String`值:
|
||||
`print`函数输出传入的`String`值:
|
||||
|
||||
```swift
|
||||
println("This is a string")
|
||||
print("This is a string")
|
||||
// 输出 "This is a string"
|
||||
```
|
||||
|
||||
与 Cocoa 里的`NSLog`函数类似的是,`println`函数可以输出更复杂的信息。这些信息可以包含当前常量和变量的值。
|
||||
与 Cocoa 里的`NSLog`函数类似的是,`print`函数可以输出更复杂的信息。这些信息可以包含当前常量和变量的值。
|
||||
|
||||
Swift 用_字符串插值(string interpolation)_的方式把常量名或者变量名当做占位符加入到长字符串中,Swift 会用当前常量或变量的值替换这些占位符。将常量或变量名放入圆括号中,并在开括号前使用反斜杠将其转义:
|
||||
|
||||
```swift
|
||||
println("The current value of friendlyWelcome is \(friendlyWelcome)")
|
||||
print("The current value of friendlyWelcome is \(friendlyWelcome)")
|
||||
// 输出 "The current value of friendlyWelcome is Bonjour!
|
||||
```
|
||||
|
||||
@ -181,7 +181,7 @@ Swift 中的注释与C 语言的注释非常相似。单行注释以双正斜杠
|
||||
与其他大部分编程语言不同,Swift 并不强制要求你在每条语句的结尾处使用分号(`;`),当然,你也可以按照你自己的习惯添加分号。有一种情况下必须要用分号,即你打算在同一行内写多条独立的语句:
|
||||
|
||||
```swift
|
||||
let cat = "🐱"; println(cat)
|
||||
let cat = "🐱"; print(cat)
|
||||
// 输出 "🐱"
|
||||
```
|
||||
|
||||
@ -409,9 +409,9 @@ let turnipsAreDelicious = false
|
||||
|
||||
```swift
|
||||
if turnipsAreDelicious {
|
||||
println("Mmm, tasty turnips!")
|
||||
print("Mmm, tasty turnips!")
|
||||
} else {
|
||||
println("Eww, turnips are horrible.")
|
||||
print("Eww, turnips are horrible.")
|
||||
}
|
||||
// 输出 "Eww, turnips are horrible."
|
||||
```
|
||||
@ -460,9 +460,9 @@ let http404Error = (404, "Not Found")
|
||||
|
||||
```swift
|
||||
let (statusCode, statusMessage) = http404Error
|
||||
println("The status code is \(statusCode)")
|
||||
print("The status code is \(statusCode)")
|
||||
// 输出 "The status code is 404"
|
||||
println("The status message is \(statusMessage)")
|
||||
print("The status message is \(statusMessage)")
|
||||
// 输出 "The status message is Not Found"
|
||||
```
|
||||
|
||||
@ -470,16 +470,16 @@ println("The status message is \(statusMessage)")
|
||||
|
||||
```swift
|
||||
let (justTheStatusCode, _) = http404Error
|
||||
println("The status code is \(justTheStatusCode)")
|
||||
print("The status code is \(justTheStatusCode)")
|
||||
// 输出 "The status code is 404"
|
||||
```
|
||||
|
||||
此外,你还可以通过下标来访问元组中的单个元素,下标从零开始:
|
||||
|
||||
```swift
|
||||
println("The status code is \(http404Error.0)")
|
||||
print("The status code is \(http404Error.0)")
|
||||
// 输出 "The status code is 404"
|
||||
println("The status message is \(http404Error.1)")
|
||||
print("The status message is \(http404Error.1)")
|
||||
// 输出 "The status message is Not Found"
|
||||
```
|
||||
|
||||
@ -492,9 +492,9 @@ let http200Status = (statusCode: 200, description: "OK")
|
||||
给元组中的元素命名后,你可以通过名字来获取这些元素的值:
|
||||
|
||||
```swift
|
||||
println("The status code is \(http200Status.statusCode)")
|
||||
print("The status code is \(http200Status.statusCode)")
|
||||
// 输出 "The status code is 200"
|
||||
println("The status message is \(http200Status.description)")
|
||||
print("The status message is \(http200Status.description)")
|
||||
// 输出 "The status message is OK"
|
||||
```
|
||||
|
||||
@ -537,9 +537,9 @@ let convertedNumber = possibleNumber.toInt()
|
||||
|
||||
```swift
|
||||
if convertedNumber != nil {
|
||||
println("\(possibleNumber) has an integer value of \(convertedNumber!)")
|
||||
print("\(possibleNumber) has an integer value of \(convertedNumber!)")
|
||||
} else {
|
||||
println("\(possibleNumber) could not be converted to an integer")
|
||||
print("\(possibleNumber) could not be converted to an integer")
|
||||
}
|
||||
// 输出 "123 has an integer value of 123"
|
||||
```
|
||||
@ -566,9 +566,9 @@ if let constantName = someOptional {
|
||||
|
||||
```swift
|
||||
if let actualNumber = possibleNumber.toInt() {
|
||||
println("\(possibleNumber) has an integer value of \(actualNumber)")
|
||||
print("\(possibleNumber) has an integer value of \(actualNumber)")
|
||||
} else {
|
||||
println("\(possibleNumber) could not be converted to an integer")
|
||||
print("\(possibleNumber) could not be converted to an integer")
|
||||
}
|
||||
// 输出 "123 has an integer value of 123"
|
||||
```
|
||||
@ -619,13 +619,13 @@ Swift 的`nil`和 Objective-C 中的`nil`并不一样。在 Objective-C 中,`n
|
||||
|
||||
```swift
|
||||
let possibleString: String? = "An optional string."
|
||||
println(possibleString!) // 需要惊叹号来获取值
|
||||
print(possibleString!) // 需要惊叹号来获取值
|
||||
// 输出 "An optional string."
|
||||
```
|
||||
|
||||
```swift
|
||||
let assumedString: String! = "An implicitly unwrapped optional string."
|
||||
println(assumedString) // 不需要感叹号
|
||||
print(assumedString) // 不需要感叹号
|
||||
// 输出 "An implicitly unwrapped optional string."
|
||||
```
|
||||
|
||||
@ -638,7 +638,7 @@ println(assumedString) // 不需要感叹号
|
||||
|
||||
```swift
|
||||
if assumedString {
|
||||
println(assumedString)
|
||||
print(assumedString)
|
||||
}
|
||||
// 输出 "An implicitly unwrapped optional string."
|
||||
```
|
||||
@ -647,7 +647,7 @@ if assumedString {
|
||||
|
||||
```swift
|
||||
if let definiteString = assumedString {
|
||||
println(definiteString)
|
||||
print(definiteString)
|
||||
}
|
||||
// 输出 "An implicitly unwrapped optional string."
|
||||
```
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
|
||||
> 翻译:[XieLingWang](https://github.com/xielingwang), [JackAlan](https://github.com/AlanMelody)
|
||||
> 校对:[EvilCome](https://github.com/Evilcome), [JackAlan](https://github.com/AlanMelody)
|
||||
> 翻译:[XieLingWang](https://github.com/xielingwang), [JackAlan](https://github.com/AlanMelody)
|
||||
> 校对:[EvilCome](https://github.com/Evilcome), [JackAlan](https://github.com/AlanMelody)
|
||||
|
||||
# 基本运算符
|
||||
-----------------
|
||||
@ -69,10 +69,10 @@ Swift 中所有数值类型都支持了基本的四则算术运算:
|
||||
- 减法(`-`)
|
||||
- 乘法(`*`)
|
||||
- 除法(`/`)
|
||||
|
||||
|
||||
1 + 2 // 等于 3
|
||||
5 - 3 // 等于 2
|
||||
2 * 3 // 等于 6
|
||||
2 * 3 // 等于 6
|
||||
10.0 / 2.5 // 等于 4.0
|
||||
|
||||
|
||||
@ -230,12 +230,12 @@ Swift 也提供恒等`===`和不恒等`!==`这两个比较符来判断两个对
|
||||
|
||||
比较运算多用于条件语句,如`if`条件:
|
||||
|
||||
|
||||
|
||||
let name = "world"
|
||||
if name == "world" {
|
||||
println("hello, world")
|
||||
print("hello, world")
|
||||
} else {
|
||||
println("I'm sorry \(name), but I don't recognize you")
|
||||
print("I'm sorry \(name), but I don't recognize you")
|
||||
}
|
||||
// 输出 "hello, world", 因为 `name` 就是等于 "world"
|
||||
|
||||
@ -256,7 +256,7 @@ Swift 也提供恒等`===`和不恒等`!==`这两个比较符来判断两个对
|
||||
}
|
||||
|
||||
这里有个计算表格行高的例子。如果有表头,那行高应比内容高度要高出50像素; 如果没有表头,只需高出20像素。
|
||||
|
||||
|
||||
let contentHeight = 40
|
||||
let hasHeader = true
|
||||
let rowHeight = contentHeight + (hasHeader ? 50 : 20)
|
||||
@ -326,7 +326,7 @@ Swift 提供了两个方便表达一个区间的值的运算符。
|
||||
闭区间运算符在迭代一个区间的所有值时是非常有用的,如在`for-in`循环中:
|
||||
|
||||
for index in 1...5 {
|
||||
println("\(index) * 5 = \(index * 5)")
|
||||
print("\(index) * 5 = \(index * 5)")
|
||||
}
|
||||
// 1 * 5 = 5
|
||||
// 2 * 5 = 10
|
||||
@ -348,7 +348,7 @@ Swift 提供了两个方便表达一个区间的值的运算符。
|
||||
let names = ["Anna", "Alex", "Brian", "Jack"]
|
||||
let count = names.count
|
||||
for i in 0..<count {
|
||||
println("第 \(i + 1) 个人叫 \(names[i])")
|
||||
print("第 \(i + 1) 个人叫 \(names[i])")
|
||||
}
|
||||
// 第 1 个人叫 Anna
|
||||
// 第 2 个人叫 Alex
|
||||
@ -375,7 +375,7 @@ Swift 提供了两个方便表达一个区间的值的运算符。
|
||||
|
||||
let allowedEntry = false
|
||||
if !allowedEntry {
|
||||
println("ACCESS DENIED")
|
||||
print("ACCESS DENIED")
|
||||
}
|
||||
// 输出 "ACCESS DENIED"
|
||||
|
||||
@ -395,9 +395,9 @@ Swift 提供了两个方便表达一个区间的值的运算符。
|
||||
let enteredDoorCode = true
|
||||
let passedRetinaScan = false
|
||||
if enteredDoorCode && passedRetinaScan {
|
||||
println("Welcome!")
|
||||
print("Welcome!")
|
||||
} else {
|
||||
println("ACCESS DENIED")
|
||||
print("ACCESS DENIED")
|
||||
}
|
||||
// 输出 "ACCESS DENIED"
|
||||
|
||||
@ -413,9 +413,9 @@ Swift 提供了两个方便表达一个区间的值的运算符。
|
||||
let hasDoorKey = false
|
||||
let knowsOverridePassword = true
|
||||
if hasDoorKey || knowsOverridePassword {
|
||||
println("Welcome!")
|
||||
print("Welcome!")
|
||||
} else {
|
||||
println("ACCESS DENIED")
|
||||
print("ACCESS DENIED")
|
||||
}
|
||||
// 输出 "Welcome!"
|
||||
|
||||
@ -424,9 +424,9 @@ Swift 提供了两个方便表达一个区间的值的运算符。
|
||||
我们可以组合多个逻辑运算来表达一个复合逻辑:
|
||||
|
||||
if enteredDoorCode && passedRetinaScan || hasDoorKey || knowsOverridePassword {
|
||||
println("Welcome!")
|
||||
print("Welcome!")
|
||||
} else {
|
||||
println("ACCESS DENIED")
|
||||
print("ACCESS DENIED")
|
||||
}
|
||||
// 输出 "Welcome!"
|
||||
|
||||
@ -445,9 +445,9 @@ Swift 逻辑操作符`&&`和`||`是左结合的,这意味着拥有多元逻辑
|
||||
|
||||
|
||||
if (enteredDoorCode && passedRetinaScan) || hasDoorKey || knowsOverridePassword {
|
||||
println("Welcome!")
|
||||
print("Welcome!")
|
||||
} else {
|
||||
println("ACCESS DENIED")
|
||||
print("ACCESS DENIED")
|
||||
}
|
||||
// 输出 "Welcome!"
|
||||
|
||||
|
||||
@ -38,26 +38,26 @@ Swift 的`String`和`Character`类型提供了一个快速的,兼容 Unicode
|
||||
<a name="string_literals"></a>
|
||||
## 字符串字面量(String Literals)
|
||||
|
||||
您可以在您的代码中包含一段预定义的字符串值作为字符串字面量。字符串字面量是由双引号 ("") 包裹着的具有固定顺序的文本字符集。
|
||||
您可以在您的代码中包含一段预定义的字符串值作为字符串字面量。字符串字面量是由双引号 ("") 包裹着的具有固定顺序的文本字符集。
|
||||
字符串字面量可以用于为常量和变量提供初始值:
|
||||
```let someString = "Some string literal value"```
|
||||
注意`someString`常量通过字符串字面量进行初始化,Swift 会推断该常量为`String`类型。
|
||||
> 注意:
|
||||
> 更多关于在字面量的特殊字符,请查看 [Special Characters in String Literals](#special_characters_in_string_literals) 。
|
||||
> 更多关于在字面量的特殊字符,请查看 [Special Characters in String Literals](#special_characters_in_string_literals) 。
|
||||
|
||||
|
||||
<a name="initializing_an_empty_string"></a>
|
||||
## 初始化空字符串 (Initializing an Empty String)
|
||||
|
||||
要创建一个空字符串作为初始值,可以将空的字符串字面量赋值给变量,也可以初始化一个新的`String`实例:
|
||||
|
||||
要创建一个空字符串作为初始值,可以将空的字符串字面量赋值给变量,也可以初始化一个新的`String`实例:
|
||||
|
||||
```swift
|
||||
var emptyString = "" // 空字符串字面量
|
||||
var anotherEmptyString = String() // 初始化方法
|
||||
// 两个字符串均为空并等价。
|
||||
```
|
||||
|
||||
您可以通过检查其`Boolean`类型的`isEmpty`属性来判断该字符串是否为空:
|
||||
您可以通过检查其`Boolean`类型的`isEmpty`属性来判断该字符串是否为空:
|
||||
```swift
|
||||
if emptyString.isEmpty {
|
||||
print("Nothing to see here")
|
||||
@ -79,7 +79,7 @@ constantString += " and another Highlander"
|
||||
// 这会报告一个编译错误 (compile-time error) - 常量不可以被修改。
|
||||
```
|
||||
|
||||
> 注意:
|
||||
> 注意:
|
||||
> 在 Objective-C 和 Cocoa 中,您需要通过选择两个不同的类(`NSString`和`NSMutableString`)来指定该字符串是否可以被修改。
|
||||
|
||||
<a name="strings_are_value_types"></a>
|
||||
@ -121,7 +121,7 @@ for-in 循环在 [For Loops](05_Control_Flow.html#for_loops) 中进行了详细
|
||||
|
||||
```swift
|
||||
let exclamationMark: Charater = "!"
|
||||
```
|
||||
```
|
||||
字符串可以通过传递一个值类型为`Charater`的数组作为自变量来初始化:
|
||||
|
||||
```swift
|
||||
@ -148,8 +148,8 @@ var welcome = string1 + string2
|
||||
```swift
|
||||
var instruction = "look over"
|
||||
instruction += string2
|
||||
// instruction 现在等于 "look over there"
|
||||
```
|
||||
// instruction 现在等于 "look over there"
|
||||
```
|
||||
|
||||
您可以用`append`方法将一个字符附加到一个字符串变量的尾部:
|
||||
|
||||
@ -160,7 +160,7 @@ welcome.append(exclamationMark)
|
||||
```
|
||||
|
||||
> 注意:
|
||||
> 您不能将一个字符串或者字符添加到一个已经存在的字符变量上,因为字符变量只能包含一个字符。
|
||||
> 您不能将一个字符串或者字符添加到一个已经存在的字符变量上,因为字符变量只能包含一个字符。
|
||||
|
||||
|
||||
<a name="string_interpolation"></a>
|
||||
@ -183,28 +183,28 @@ let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"
|
||||
在这个例子中,表达式写为`\(Double(multiplier) * 2.5)`并包含在字符串字面量中。
|
||||
|
||||
> 注意:
|
||||
> 插值字符串中写在括号中的表达式不能包含非转义双引号 (`"`) 和反斜杠 (`\`),并且不能包含回车或换行符。
|
||||
> 插值字符串中写在括号中的表达式不能包含非转义双引号 (`"`) 和反斜杠 (`\`),并且不能包含回车或换行符。
|
||||
|
||||
|
||||
<a name="unicode"></a>
|
||||
<a name="unicode"></a>
|
||||
## Unicode
|
||||
|
||||
Unicode 是一个国际标准,用于文本的编码和表示。
|
||||
它使您可以用标准格式表示来自任意语言几乎所有的字符,并能够对文本文件或网页这样的外部资源中的字符进行读写操作。
|
||||
Swift 的字符串和字符类型是完全兼容 Unicode 标准的。
|
||||
|
||||
<a name="unicode_scalars"></a>
|
||||
### Unicode 标量(Unicode Scalars)
|
||||
<a name="unicode_scalars"></a>
|
||||
### Unicode 标量(Unicode Scalars)
|
||||
|
||||
Swift 的`String`类型是基于 *Unicode 标量* 建立的。
|
||||
Unicode 标量是对应字符的唯一21位数字或者修饰符,例如`U+0061`表示小写的拉丁字母(`LATIN SMALL LETTER A`)("`a`"),`U+1F425`表示小鸡表情(`FRONT-FACING BABY CHICK`) ("`🐥`")
|
||||
> 注意:
|
||||
Unicode 标量是对应字符的唯一21位数字或者修饰符,例如`U+0061`表示小写的拉丁字母(`LATIN SMALL LETTER A`)("`a`"),`U+1F425`表示小鸡表情(`FRONT-FACING BABY CHICK`) ("`🐥`")
|
||||
> 注意:
|
||||
> Unicode *码位(code poing)* 的范围是`U+0000`到`U+D7FF`或者`U+E000`到`U+10FFFF`。Unicode 标量不包括 Unicode *代理项(surrogate pair)* 码位,其码位范围是`U+D800`到`U+DFFF`。
|
||||
|
||||
注意不是所有的21位 Unicode 标量都代表一个字符,因为有一些标量是保留给未来分配的。已经代表一个典型字符的标量都有自己的名字,例如上面例子中的`LATIN SMALL LETTER A`和`FRONT-FACING BABY CHICK`。
|
||||
注意不是所有的21位 Unicode 标量都代表一个字符,因为有一些标量是保留给未来分配的。已经代表一个典型字符的标量都有自己的名字,例如上面例子中的`LATIN SMALL LETTER A`和`FRONT-FACING BABY CHICK`。
|
||||
|
||||
<a name="special_characters_in_string_literals"></a>
|
||||
### 字符串字面量的特殊字符 (Special Characters in String Literals)
|
||||
<a name="special_characters_in_string_literals"></a>
|
||||
### 字符串字面量的特殊字符 (Special Characters in String Literals)
|
||||
|
||||
字符串字面量可以包含以下特殊字符:
|
||||
|
||||
@ -221,42 +221,42 @@ let wiseWords = "\"Imagination is more important than knowledge\" - Einstein"
|
||||
let dollarSign = "\u{24}" // $, Unicode 标量 U+0024
|
||||
let blackHeart = "\u{2665}" // ♥, Unicode 标量 U+2665
|
||||
let sparklingHeart = "\u{1F496}" // 💖, Unicode 标量 U+1F496
|
||||
```
|
||||
```
|
||||
|
||||
<a name="extended_grapheme_clusters"></a>
|
||||
### 可扩展的字形群集(Extended Grapheme Clusters)
|
||||
### 可扩展的字形群集(Extended Grapheme Clusters)
|
||||
每一个 Swift 的`Character`类型代表一个可扩展的字形群。
|
||||
一个可扩展的字形群是一个或者更多可生成人类可读的字符 Unicode 标量的有序排列。
|
||||
一个可扩展的字形群是一个或者更多可生成人类可读的字符 Unicode 标量的有序排列。
|
||||
举个例子,字母 é 可以用单一的 Unicode 标量 é (`LATIN SMALL LETTER E WITH ACUTE`, 或者`U+00E9`)来表示。然而一个标准的字母 e (`LATIN SMALL LETTER E`或者`U+0065`) 加上一个急促重音(`COMBINING ACTUE ACCENT`)的标量(`U+0301`),这样一对标量就表示了同样的字母 é。
|
||||
这个急促重音的标量形象的将 e 转换成了 é。
|
||||
这个急促重音的标量形象的将 e 转换成了 é。
|
||||
在这两种情况中,字母 é 代表了一个单一的 Swift 的字符串,同时代表了一个可扩展的字形群。
|
||||
在第一种情况,这个字形群包含一个单一标量;而在第二种情况,它是包含两个标量的字形群:
|
||||
在第一种情况,这个字形群包含一个单一标量;而在第二种情况,它是包含两个标量的字形群:
|
||||
|
||||
```swift
|
||||
let eAcute: Character = "\u{E9}" // é
|
||||
let combinedEAcute: Character = "\u{65}\u{301}" // e 后面加上 ́
|
||||
// eAcute 是 é, combinedEAcute 是 é
|
||||
```
|
||||
```
|
||||
|
||||
可扩展的字符群集是一个灵活的方法,用许多复杂的脚本字符表示单一字符。
|
||||
例如,来自朝鲜语字母表的韩语音节能表示为组合或分解的有序排列。
|
||||
在 Swift 都会表示为同一个单一的字符:
|
||||
在 Swift 都会表示为同一个单一的字符:
|
||||
|
||||
|
||||
```swift
|
||||
let precomposed: Character = "\u{D55C}" // 한
|
||||
let decomposed: Character = "\u{1112}\u{1161}\u{11AB}" // ᄒ, ᅡ, ᆫ
|
||||
// precomposed 是 한, decomposed 是 한
|
||||
```
|
||||
```
|
||||
|
||||
可拓展的字符群集可以使包围记号(例如`COMBINING ENCLOSING CIRCLE`或者`U+20DD`)的标量包围其他 Unicode 标量,作为一个单一的字符:
|
||||
可拓展的字符群集可以使包围记号(例如`COMBINING ENCLOSING CIRCLE`或者`U+20DD`)的标量包围其他 Unicode 标量,作为一个单一的字符:
|
||||
|
||||
```swift
|
||||
let enclosedEAcute: Character = "\u{E9}\u{20DD}"
|
||||
// enclosedEAcute 是 é⃝
|
||||
```
|
||||
|
||||
局部的指示符号的 Unicode 标量可以组合成一个单一的字符,例如 `REGIONAL INDICATOR SYMBOL LETTER U`(`U+1F1FA`)和`REGIONAL INDICATOR SYMBOL LETTER S`(`U+1F1F8`):
|
||||
局部的指示符号的 Unicode 标量可以组合成一个单一的字符,例如 `REGIONAL INDICATOR SYMBOL LETTER U`(`U+1F1FA`)和`REGIONAL INDICATOR SYMBOL LETTER S`(`U+1F1F8`):
|
||||
|
||||
|
||||
```swift
|
||||
@ -276,7 +276,7 @@ print("unusualMenagerie has \(unusualMenagerie.characters.count) characters")
|
||||
// 打印输出:"unusualMenagerie has 40 characters"
|
||||
```
|
||||
|
||||
注意在 Swift 中,使用可拓展的字符群集作为字符来连接或改变字符串时,并不一定会更改字符串的字符数量。
|
||||
注意在 Swift 中,使用可拓展的字符群集作为字符来连接或改变字符串时,并不一定会更改字符串的字符数量。
|
||||
例如,如果你用四个字符的单词 cafe 初始化一个新的字符串,然后添加一个 `COMBINING ACTUE ACCENT`(`U+0301`)作为字符串的结尾。最终这个字符串的字符数量仍然是4,因为第四个字符是 é ,而不是 e :
|
||||
|
||||
```swift
|
||||
@ -290,20 +290,20 @@ print("the number of characters in \(word) is \(word.characters.count)")
|
||||
|
||||
> 注意:
|
||||
> 可扩展的字符群集可以组成一个或者多个 Unicode 标量。这意味着不同的字符以及相同字符的不同表示方式可能需要不同数量的内存空间来存储。所以 Swift 中的字符在一个字符串中并不一定占用相同的内存空间数量。因此在没有获取字符串的可扩展的字符群的范围时候,就不能计算出字符串的字符数量。如果您正在处理一个长字符串,需要注意`characters`属性必须遍历全部的 Unicode 标量,来确定字符串的字符数量。
|
||||
> 另外需要注意的是通过`characters`返回的字符数量并不总是与包含相同字符的`NSString`的`length`属性相同。`NSString`的`length`属性是利用 UTF-16 表示的十六位代码单元数字,而不是 Unicode 可扩展的字符群集。
|
||||
> 另外需要注意的是通过`characters`返回的字符数量并不总是与包含相同字符的`NSString`的`length`属性相同。`NSString`的`length`属性是利用 UTF-16 表示的十六位代码单元数字,而不是 Unicode 可扩展的字符群集。
|
||||
|
||||
|
||||
<a name="accessing_and_modifying_a_string"></a>
|
||||
## 访问和修改字符串 (Accessing and Modifying a String)
|
||||
你可以通字符串的属性和方法来访问和读取一个它,当然也可以用下标语法完成。
|
||||
<a name="accessing_and_modifying_a_string"></a>
|
||||
## 访问和修改字符串 (Accessing and Modifying a String)
|
||||
你可以通字符串的属性和方法来访问和读取一个它,当然也可以用下标语法完成。
|
||||
|
||||
<a name="string_indices"></a>
|
||||
### 字符串索引 (String Indices)
|
||||
每一个字符串都有一个关联的索引(*index*)类型,`String.index`,它对应着字符串中的每一个字符的位置。
|
||||
前面提到,不同的字符可能会占用不同的内存空间数量,所以要知道字符的确定位置,就必须从字符串开头遍历每一个 Unicode 标量到字符串结尾。因此,Swift 的字符串不能用整数(integer)做索引。
|
||||
使用`startIndex`属性可以获取字符串的第一个字符。使用`endIndex`属性可以获取最后一个字符的末尾位置。如果字符串是空值,`startIndex`和`endIndex`是相等的。
|
||||
通过调用`String.Index`的`predecessor()`方法,可以立即得到前面一个索引,调用`successor()`方法可以立即得到后面一个索引。任何一个字符串的索引都可以通过锁链作用的这些方法来获取另一个索引,也可以调用`advance(start:n:)`函数来获取。但如果尝试获取出界的字符串索引,就会抛出一个运行时错误。
|
||||
你可以使用下标语法来访问字符在字符串的确切索引。尝试获取出界的字符串索引,仍然抛出一个运行时错误。
|
||||
### 字符串索引 (String Indices)
|
||||
每一个字符串都有一个关联的索引(*index*)类型,`String.index`,它对应着字符串中的每一个字符的位置。
|
||||
前面提到,不同的字符可能会占用不同的内存空间数量,所以要知道字符的确定位置,就必须从字符串开头遍历每一个 Unicode 标量到字符串结尾。因此,Swift 的字符串不能用整数(integer)做索引。
|
||||
使用`startIndex`属性可以获取字符串的第一个字符。使用`endIndex`属性可以获取最后一个字符的末尾位置。如果字符串是空值,`startIndex`和`endIndex`是相等的。
|
||||
通过调用`String.Index`的`predecessor()`方法,可以立即得到前面一个索引,调用`successor()`方法可以立即得到后面一个索引。任何一个字符串的索引都可以通过锁链作用的这些方法来获取另一个索引,也可以调用`advance(start:n:)`函数来获取。但如果尝试获取出界的字符串索引,就会抛出一个运行时错误。
|
||||
你可以使用下标语法来访问字符在字符串的确切索引。尝试获取出界的字符串索引,仍然抛出一个运行时错误。
|
||||
|
||||
```swift
|
||||
let greeting = "Guten Tag"
|
||||
@ -318,43 +318,43 @@ greeting[index]
|
||||
// a
|
||||
greeting[greeting.endIndex] // 错误
|
||||
greeting.endIndex.successor() // 错误
|
||||
```
|
||||
```
|
||||
|
||||
使用`characters`属性的`indices`会创建一个包含全部索引的范围(`Range`),用来在一个字符串中访问分立的字符。
|
||||
|
||||
|
||||
```swift
|
||||
for index in greeting.characters.indices {
|
||||
print("\(greeting[index]) ", appendNewline: false)
|
||||
}
|
||||
// 打印输出 "G u t e n T a g !"
|
||||
```
|
||||
```
|
||||
|
||||
<a name="inserting_and_removing"></a>
|
||||
### 插入和删除 (Inserting and Removing)
|
||||
调用`insert(_:atIndex:)`方法可以在一个字符串的指定索引插入一个字符。
|
||||
<a name="inserting_and_removing"></a>
|
||||
### 插入和删除 (Inserting and Removing)
|
||||
调用`insert(_:atIndex:)`方法可以在一个字符串的指定索引插入一个字符。
|
||||
|
||||
```swift
|
||||
var welcome = "hello"
|
||||
welcome.insert("!", atIndex: welcome.endIndex)
|
||||
// welcome now 现在等于 "hello!"
|
||||
```
|
||||
// welcome now 现在等于 "hello!"
|
||||
```
|
||||
|
||||
调用`splice(_:atIndex:)`方法可以在一个字符串的指定索引插入一个字符串。
|
||||
调用`splice(_:atIndex:)`方法可以在一个字符串的指定索引插入一个字符串。
|
||||
|
||||
```swift
|
||||
welcome.splice(" there".characters, atIndex: welcome.endIndex.predecessor())
|
||||
// welcome 现在等于 "hello there!"
|
||||
```
|
||||
```
|
||||
|
||||
调用`removeAtIndex(_:)`方法可以在一个字符串的指定索引删除一个字符。
|
||||
调用`removeAtIndex(_:)`方法可以在一个字符串的指定索引删除一个字符。
|
||||
|
||||
```swift
|
||||
welcome.removeAtIndex(welcome.endIndex.predecessor())
|
||||
// welcome 现在等于 "hello there"
|
||||
// 翻译的人解释:最后还有一个换行符,所以这里删除的是 !
|
||||
```
|
||||
```
|
||||
|
||||
调用`removeRange(_:)`方法可以在一个字符串的指定索引删除一个子字符串。
|
||||
调用`removeRange(_:)`方法可以在一个字符串的指定索引删除一个子字符串。
|
||||
|
||||
```swift
|
||||
let range = advance(welcome.endIndex, -6)..<welcome.endIndex
|
||||
@ -369,7 +369,7 @@ welcome.removeRange(range)
|
||||
Swift 提供了三种方式来比较文本值:字符串字符相等、前缀相等和后缀相等。
|
||||
|
||||
<a name="string_and_character_equality"></a>
|
||||
### 字符串/字符相等 (String and Character Equality)
|
||||
### 字符串/字符相等 (String and Character Equality)
|
||||
字符串/字符可以用等于操作符(`==`)和不等于操作符(`!=`),详细描述在 [Comparison Operators](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/BasicOperators.html#//apple_ref/doc/uid/TP40014097-CH6-ID70):
|
||||
|
||||
```swift
|
||||
@ -379,10 +379,10 @@ if quotation == sameQuotation {
|
||||
print("These two strings are considered equal")
|
||||
}
|
||||
// 打印输出 "These two strings are considered equal"
|
||||
```
|
||||
```
|
||||
|
||||
如果两个字符串(或者两个字符)的可扩展的字形群集是标准相等的,那就认为它们是相等的。在这个情况下,即使可扩展的字形群集是有不同的 Unicode 标量构成的,只要它们有同样的语言意义和外观,就认为它们标准相等。
|
||||
例如,`LATIN SMALL LETTER E WITH ACUTE`(`U+00E9`)就是标准相等于`LATIN SMALL LETTER E`(`U+0065`)后面加上`COMBINING ACUTE ACCENT`(`U+0301`)。这两个字符群集都有效的表示字符 é ,所以它们被认为是标准相等的:
|
||||
如果两个字符串(或者两个字符)的可扩展的字形群集是标准相等的,那就认为它们是相等的。在这个情况下,即使可扩展的字形群集是有不同的 Unicode 标量构成的,只要它们有同样的语言意义和外观,就认为它们标准相等。
|
||||
例如,`LATIN SMALL LETTER E WITH ACUTE`(`U+00E9`)就是标准相等于`LATIN SMALL LETTER E`(`U+0065`)后面加上`COMBINING ACUTE ACCENT`(`U+0301`)。这两个字符群集都有效的表示字符 é ,所以它们被认为是标准相等的:
|
||||
|
||||
```swift
|
||||
// "Voulez-vous un café?" 使用 LATIN SMALL LETTER E WITH ACUTE
|
||||
@ -393,9 +393,9 @@ if eAcuteQuestion == combinedEAcuteQuestion {
|
||||
print("These two strings are considered equal")
|
||||
}
|
||||
// 打印输出 "These two strings are considered equal"
|
||||
```
|
||||
```
|
||||
|
||||
相反,英语中的`LATIN CAPITAL LETTER A`(`U+0401`,或者`A`)不等于俄语中的`CYRILLIC CAPITAL LETTER A`(`U+0410`,或者`A`)。两个字符看着是一样的,但却有不同的语言意义:
|
||||
相反,英语中的`LATIN CAPITAL LETTER A`(`U+0401`,或者`A`)不等于俄语中的`CYRILLIC CAPITAL LETTER A`(`U+0410`,或者`A`)。两个字符看着是一样的,但却有不同的语言意义:
|
||||
|
||||
```swift
|
||||
let latinCapitalLetterA: Character = "\u{41}"
|
||||
@ -404,16 +404,16 @@ if latinCapitalLetterA != cyrillicCapitalLetterA {
|
||||
print("These two characters are not equivalent")
|
||||
}
|
||||
// 打印 "These two characters are not equivalent"
|
||||
```
|
||||
```
|
||||
|
||||
> 注意:
|
||||
> 在 Swift 中,字符串和字符并不区分区域。
|
||||
> 在 Swift 中,字符串和字符并不区分区域。
|
||||
|
||||
|
||||
<a name="prefix_and_suffix_equality"></a>
|
||||
### 前缀/后缀相等 (Prefix and Suffix Equality)
|
||||
|
||||
通过调用字符串的`hasPrefix(_:)`/`hasSuffix(_:)`方法来检查字符串是否拥有特定前缀/后缀,两个方法均需要以字符串作为参数传入并传出`Boolean`值。
|
||||
通过调用字符串的`hasPrefix(_:)`/`hasSuffix(_:)`方法来检查字符串是否拥有特定前缀/后缀,两个方法均需要以字符串作为参数传入并传出`Boolean`值。
|
||||
下面的例子以一个字符串数组表示莎士比亚话剧《罗密欧与朱丽叶》中前两场的场景位置:
|
||||
|
||||
```swift
|
||||
@ -459,14 +459,14 @@ for scene in romeoAndJuliet {
|
||||
}
|
||||
print("\(mansionCount) mansion scenes; \(cellCount) cell scenes")
|
||||
// 打印输出 "6 mansion scenes; 2 cell scenes"
|
||||
```
|
||||
```
|
||||
|
||||
> 注意:
|
||||
> `hasPrefix(_:)`和`hasSuffix(_:)`方法都是在每个字符串中一个一个字符的比较其可扩展的字符群集是否标准相等,详细描述在[字符串/字符相等](#string_and_character_equality)。
|
||||
> `hasPrefix(_:)`和`hasSuffix(_:)`方法都是在每个字符串中一个一个字符的比较其可扩展的字符群集是否标准相等,详细描述在[字符串/字符相等](#string_and_character_equality)。
|
||||
|
||||
|
||||
<a name="unicode_representations_of_strings"></a>
|
||||
## 字符串的 Unicode 表示形式(Unicode Representations of Strings)
|
||||
## 字符串的 Unicode 表示形式(Unicode Representations of Strings)
|
||||
当一个 Unicode 字符串被写进文本文件或者其他储存时,字符串中的 Unicode 标量会用 Unicode 定义的几种编码格式编码。每一个字符串中的小块编码都被称为代码单元。这些包括 UTF-8 编码格式(编码字符串为8位的代码单元), UTF-16 编码格式(编码字符串位16位的代码单元),以及 UTF-32 编码格式(编码字符串32位的代码单元)。
|
||||
|
||||
Swift 提供了几种不同的方式来访问字符串的 Unicode 表示形式。
|
||||
@ -483,13 +483,13 @@ Swift 提供了几种不同的方式来访问字符串的 Unicode 表示形式
|
||||
|
||||
```swift
|
||||
let dogString = "Dog‼🐶"
|
||||
```
|
||||
```
|
||||
|
||||
|
||||
<a name="UTF-8_representation"></a>
|
||||
### UTF-8 表示
|
||||
### UTF-8 表示
|
||||
您可以通过遍历字符串的`utf8`属性来访问它的`UTF-8`表示。
|
||||
其为`String.UTF8View`类型的属性,`UTF8View`是无符号8位 (`UInt8`) 值的集合,每一个`UInt8`值都是一个字符的 UTF-8 表示:
|
||||
其为`String.UTF8View`类型的属性,`UTF8View`是无符号8位 (`UInt8`) 值的集合,每一个`UInt8`值都是一个字符的 UTF-8 表示:
|
||||
|
||||
<body>
|
||||
<center>
|
||||
@ -542,14 +542,14 @@ print("")
|
||||
|
||||
上面的例子中,前三个10进制代码单元值 (68, 111, 103) 代表了字符`D`、`o`和 `g`,它们的 UTF-8 表示与 ASCII 表示相同。
|
||||
接下来的三个10进制代码单元值 (226, 128, 188) 是`DOUBLE EXCLAMATION MARK`的3字节 UTF-8 表示。
|
||||
最后的四个代码单元值 (240, 159, 144, 182) 是`DOG FACE`的4字节 UTF-8 表示。
|
||||
最后的四个代码单元值 (240, 159, 144, 182) 是`DOG FACE`的4字节 UTF-8 表示。
|
||||
|
||||
|
||||
<a name="UTF-16_representation"></a>
|
||||
### UTF-16 表示
|
||||
|
||||
您可以通过遍历字符串的`utf16`属性来访问它的`UTF-16`表示。
|
||||
其为`String.UTF16View`类型的属性,`UTF16View`是无符号16位 (`UInt16`) 值的集合,每一个`UInt16`都是一个字符的 UTF-16 表示:
|
||||
其为`String.UTF16View`类型的属性,`UTF16View`是无符号16位 (`UInt16`) 值的集合,每一个`UInt16`都是一个字符的 UTF-16 表示:
|
||||
<body>
|
||||
<center>
|
||||
<table style='text-align:center'>
|
||||
@ -581,7 +581,7 @@ print("")
|
||||
</tr>
|
||||
</table>
|
||||
</center>
|
||||
</body>
|
||||
</body>
|
||||
|
||||
|
||||
```swift
|
||||
@ -592,8 +592,8 @@ print("")
|
||||
// 68 111 103 8252 55357 56374
|
||||
```
|
||||
|
||||
同样,前三个代码单元值 (68, 111, 103) 代表了字符`D`、`o`和`g`,它们的 UTF-16 代码单元和 UTF-8 完全相同(因为这些 Unicode 标量表示 ASCII 字符)。
|
||||
第四个代码单元值 (8252) 是一个等于十六进制203C的的十进制值。这个代表了`DOUBLE EXCLAMATION MARK`字符的 Unicode 标量值`U+203C`。这个字符在 UTF-16 中可以用一个代码单元表示。
|
||||
同样,前三个代码单元值 (68, 111, 103) 代表了字符`D`、`o`和`g`,它们的 UTF-16 代码单元和 UTF-8 完全相同(因为这些 Unicode 标量表示 ASCII 字符)。
|
||||
第四个代码单元值 (8252) 是一个等于十六进制203C的的十进制值。这个代表了`DOUBLE EXCLAMATION MARK`字符的 Unicode 标量值`U+203C`。这个字符在 UTF-16 中可以用一个代码单元表示。
|
||||
第五和第六个代码单元值 (55357 和 56374) 是`DOG FACE`字符的UTF-16 表示。
|
||||
第一个值为`U+D83D`(十进制值为 55357),第二个值为`U+DC36`(十进制值为 56374)。
|
||||
|
||||
@ -604,7 +604,7 @@ print("")
|
||||
其为`UnicodeScalarView`类型的属性, `UnicodeScalarView`是`UnicodeScalar`的集合。
|
||||
`UnicodeScalar`是21位的 Unicode 代码点。
|
||||
|
||||
每一个`UnicodeScalar`拥有一个值属性,可以返回对应的21位数值,用`UInt32`来表示:
|
||||
每一个`UnicodeScalar`拥有一个值属性,可以返回对应的21位数值,用`UInt32`来表示:
|
||||
|
||||
<body>
|
||||
<center>
|
||||
@ -635,7 +635,7 @@ print("")
|
||||
</tr>
|
||||
</table>
|
||||
</center>
|
||||
</body>
|
||||
</body>
|
||||
|
||||
|
||||
```swift
|
||||
@ -646,8 +646,8 @@ print("")
|
||||
// 68 111 103 8252 128054
|
||||
```
|
||||
|
||||
前三个代码单元值 (68, 111, 103) 仍然代表字符`D`、`o`和`g`。
|
||||
第四个代码单元值 (8252) 仍然是一个等于十六进制203C的的十进制值。这个代表了`DOUBLE EXCLAMATION MARK`字符的 Unicode 标量`U+203C`。
|
||||
前三个代码单元值 (68, 111, 103) 仍然代表字符`D`、`o`和`g`。
|
||||
第四个代码单元值 (8252) 仍然是一个等于十六进制203C的的十进制值。这个代表了`DOUBLE EXCLAMATION MARK`字符的 Unicode 标量`U+203C`。
|
||||
第五位数值,128054,是一个十六进制1F436的十进制表示。其等同于`DOG FACE`的Unicode 标量`U+1F436`。
|
||||
|
||||
作为查询字符值属性的一种替代方法,每个`UnicodeScalar`值也可以用来构建一个新的字符串值,比如在字符串插值中使用:
|
||||
@ -661,4 +661,4 @@ for scalar in dogString.unicodeScalars {
|
||||
// g
|
||||
// ‼
|
||||
// 🐶
|
||||
```
|
||||
```
|
||||
|
||||
@ -751,7 +751,7 @@ Swift 有内置支持去检查接口的可用性的,这可以确保我们不
|
||||
|
||||
```swift
|
||||
if #available(iOS 9, OSX 10.10, *) {
|
||||
// 在 iOS 使用 iOS 9 APIs , 并且在 OS X 使用 OS X v10.10 APIs
|
||||
// 在 iOS 使用 iOS 9 APIs , 并且在 OS X 使用 OS X v10.10 APIs
|
||||
} else {
|
||||
// 回滚至早前 iOS and OS X 的API
|
||||
}
|
||||
@ -767,4 +767,4 @@ if #available(`platform name` `version`, `...`, *) {
|
||||
} else {
|
||||
`fallback statements to execute if the APIs are unavailable`
|
||||
}
|
||||
```
|
||||
```
|
||||
|
||||
@ -39,13 +39,13 @@ func sayHello(personName: String) -> String {
|
||||
该定义描述了函数做什么,它期望接收什么和执行结束时它返回的结果是什么。这样的定义使得函数可以在别的地方以一种清晰的方式被调用:
|
||||
|
||||
```swift
|
||||
println(sayHello("Anna"))
|
||||
print(sayHello("Anna"))
|
||||
// prints "Hello, Anna!"
|
||||
println(sayHello("Brian"))
|
||||
print(sayHello("Brian"))
|
||||
// prints "Hello, Brian!"
|
||||
```
|
||||
|
||||
调用 `sayHello(_:)` 函数时,在圆括号中传给它一个 `String` 类型的实参。因为这个函数返回一个 `String` 类型的值,`sayHello` 可以被包含在 `println` 的调用中,用来输出这个函数的返回值,正如上面所示。
|
||||
调用 `sayHello(_:)` 函数时,在圆括号中传给它一个 `String` 类型的实参。因为这个函数返回一个 `String` 类型的值,`sayHello` 可以被包含在 `print` 的调用中,用来输出这个函数的返回值,正如上面所示。
|
||||
|
||||
在 `sayHello(_:)` 的函数体中,先定义了一个新的名为 `greeting` 的 `String` 常量,同时赋值了给 `personName` 的一个简单问候消息。然后用 `return` 关键字把这个问候返回出去。一旦 `return greeting` 被调用,该函数结束它的执行并返回 `greeting` 的当前值。
|
||||
|
||||
@ -57,7 +57,7 @@ println(sayHello("Brian"))
|
||||
func sayHelloAgain(personName: String) -> String {
|
||||
return "Hello again, " + personName + "!"
|
||||
}
|
||||
println(sayHelloAgain("Anna"))
|
||||
print(sayHelloAgain("Anna"))
|
||||
// prints "Hello again, Anna!"
|
||||
```
|
||||
|
||||
@ -76,7 +76,7 @@ println(sayHelloAgain("Anna"))
|
||||
func halfOpenRangeLength(start: Int, end: Int) -> Int {
|
||||
return end - start
|
||||
}
|
||||
println(halfOpenRangeLength(1, 10))
|
||||
print(halfOpenRangeLength(1, 10))
|
||||
// prints "9"
|
||||
```
|
||||
|
||||
@ -88,7 +88,7 @@ println(halfOpenRangeLength(1, 10))
|
||||
func sayHelloWorld() -> String {
|
||||
return "hello, world"
|
||||
}
|
||||
println(sayHelloWorld())
|
||||
print(sayHelloWorld())
|
||||
// prints "hello, world"
|
||||
```
|
||||
|
||||
@ -122,7 +122,7 @@ print(sayHello("Tim", alreadyGreeted: true))
|
||||
|
||||
```swift
|
||||
func sayGoodbye(personName: String) {
|
||||
println("Goodbye, \(personName)!")
|
||||
print("Goodbye, \(personName)!")
|
||||
}
|
||||
sayGoodbye("Dave")
|
||||
// prints "Goodbye, Dave!"
|
||||
|
||||
@ -98,7 +98,7 @@ let someVideoMode = VideoMode()
|
||||
通过使用*点语法*(*dot syntax*),你可以访问实例中所含有的属性。其语法规则是,实例名后面紧跟属性名,两者通过点号(.)连接:
|
||||
|
||||
```swift
|
||||
println("The width of someResolution is \(someResolution.width)")
|
||||
print("The width of someResolution is \(someResolution.width)")
|
||||
// 输出 "The width of someResolution is 0"
|
||||
```
|
||||
|
||||
@ -107,7 +107,7 @@ println("The width of someResolution is \(someResolution.width)")
|
||||
你也可以访问子属性,如`VideoMode`中`Resolution`属性的`width`属性:
|
||||
|
||||
```swift
|
||||
println("The width of someVideoMode is \(someVideoMode.resolution.width)")
|
||||
print("The width of someVideoMode is \(someVideoMode.resolution.width)")
|
||||
// 输出 "The width of someVideoMode is 0"
|
||||
```
|
||||
|
||||
@ -115,7 +115,7 @@ println("The width of someVideoMode is \(someVideoMode.resolution.width)")
|
||||
|
||||
```swift
|
||||
someVideoMode.resolution.width = 1280
|
||||
println("The width of someVideoMode is now \(someVideoMode.resolution.width)")
|
||||
print("The width of someVideoMode is now \(someVideoMode.resolution.width)")
|
||||
// 输出 "The width of someVideoMode is now 1280"
|
||||
```
|
||||
|
||||
@ -161,14 +161,14 @@ cinema.width = 2048
|
||||
这里,将会显示`cinema`的`width`属性确已改为了`2048`:
|
||||
|
||||
```swift
|
||||
println("cinema is now \(cinema.width) pixels wide")
|
||||
print("cinema is now \(cinema.width) pixels wide")
|
||||
// 输出 "cinema is now 2048 pixels wide"
|
||||
```
|
||||
|
||||
然而,初始的`hd`实例中`width`属性还是`1920`:
|
||||
|
||||
```swift
|
||||
println("hd is still \(hd.width ) pixels wide")
|
||||
print("hd is still \(hd.width ) pixels wide")
|
||||
// 输出 "hd is still 1920 pixels wide"
|
||||
```
|
||||
|
||||
@ -184,7 +184,7 @@ var currentDirection = CompassPoint.West
|
||||
let rememberedDirection = currentDirection
|
||||
currentDirection = .East
|
||||
if rememberedDirection == .West {
|
||||
println("The remembered direction is still .West")
|
||||
print("The remembered direction is still .West")
|
||||
}
|
||||
// 输出 "The remembered direction is still .West"
|
||||
```
|
||||
@ -220,7 +220,7 @@ alsoTenEighty.frameRate = 30.0
|
||||
下面,通过查看`tenEighty`的`frameRate`属性,我们会发现它正确的显示了基本`VideoMode`实例的新帧率,其值为`30.0`:
|
||||
|
||||
```swift
|
||||
println("The frameRate property of tenEighty is now \(tenEighty.frameRate)")
|
||||
print("The frameRate property of tenEighty is now \(tenEighty.frameRate)")
|
||||
// 输出 "The frameRate property of theEighty is now 30.0"
|
||||
```
|
||||
|
||||
@ -239,7 +239,7 @@ println("The frameRate property of tenEighty is now \(tenEighty.frameRate)")
|
||||
|
||||
```swift
|
||||
if tenEighty === alsoTenEighty {
|
||||
println("tenEighty and alsoTenEighty refer to the same Resolution instance.")
|
||||
print("tenEighty and alsoTenEighty refer to the same Resolution instance.")
|
||||
}
|
||||
//输出 "tenEighty and alsoTenEighty refer to the same Resolution instance."
|
||||
```
|
||||
@ -288,4 +288,3 @@ Objective-C中`字符串(NSString)`,`数组(NSArray)`和`字典(NSDict
|
||||
> 注意:
|
||||
以上是对于字符串、数组、字典和其它值的`拷贝`的描述。
|
||||
在你的代码中,拷贝好像是确实是在有拷贝行为的地方产生过。然而,在 Swift 的后台中,只有确有必要,`实际(actual)`拷贝才会被执行。Swift 管理所有的值拷贝以确保性能最优化的性能,所以你也没有必要去避免赋值以保证最优性能。(实际赋值由系统管理优化)
|
||||
|
||||
|
||||
@ -62,7 +62,7 @@ class Counter {
|
||||
|
||||
函数参数可以同时有一个局部名称(在函数体内部使用)和一个外部名称(在调用函数时使用),详情参见[函数的外部参数名](06_Functions.html)。方法参数也一样(因为方法就是函数,只是这个函数与某个类型相关联了)。
|
||||
|
||||
Swift 中的方法和 Objective-C 中的方法极其相似。像在 Objective-C 中一样,Swift 中方法的名称通常用一个介词指向方法的第一个参数,比如:`with`,`for`,`by`等等。前面的`Counter`类的例子中`incrementBy(_:)`方法就是这样的。介词的使用让方法在被调用时能像一个句子一样被解读。
|
||||
Swift 中的方法和 Objective-C 中的方法极其相似。像在 Objective-C 中一样,Swift 中方法的名称通常用一个介词指向方法的第一个参数,比如:`with`,`for`,`by`等等。前面的`Counter`类的例子中`incrementBy(_:)`方法就是这样的。介词的使用让方法在被调用时能像一个句子一样被解读。
|
||||
|
||||
具体来说,Swift 默认仅给方法的第一个参数名称一个局部参数名称;默认同时给第二个和后续的参数名称局部参数名称和外部参数名称。这个约定与典型的命名和调用约定相适应,与你在写 Objective-C 的方法时很相似。这个约定还让表达式方法在调用时不需要再限定参数名称。
|
||||
|
||||
@ -85,7 +85,7 @@ counter.incrementBy(5, numberOfTimes: 3)
|
||||
// counter 的值现在是 15
|
||||
```
|
||||
|
||||
你不必为第一个参数值再定义一个外部变量名:因为从函数名`incrementBy(_numberOfTimes:)`已经能很清楚地看出它的作用。但是第二个参数,就要被一个外部参数名称所限定,以便在方法被调用时明确它的作用。
|
||||
你不必为第一个参数值再定义一个外部变量名:因为从函数名`incrementBy(_numberOfTimes:)`已经能很清楚地看出它的作用。但是第二个参数,就要被一个外部参数名称所限定,以便在方法被调用时明确它的作用。
|
||||
这种默认行为使上面代码意味着:在 Swift 中定义方法使用了与 Objective-C 同样的语法风格,并且方法将以自然表达式的方式被调用。
|
||||
|
||||
|
||||
|
||||
@ -54,7 +54,7 @@ struct TimesTable {
|
||||
}
|
||||
}
|
||||
let threeTimesTable = TimesTable(multiplier: 3)
|
||||
println("3的6倍是\(threeTimesTable[6])")
|
||||
print("3的6倍是\(threeTimesTable[6])")
|
||||
// 输出 "3的6倍是18"
|
||||
```
|
||||
|
||||
|
||||
@ -49,7 +49,7 @@ let someVehicle = Vehicle()
|
||||
现在已经创建了一个`Vehicle`的新实例,你可以访问它的`description`属性来打印车辆的当前速度。
|
||||
|
||||
```swift
|
||||
println("Vehicle: \(someVehicle.description)")
|
||||
print("Vehicle: \(someVehicle.description)")
|
||||
// Vehicle: traveling at 0.0 miles per hour
|
||||
```
|
||||
|
||||
@ -81,17 +81,17 @@ class Bicycle: Vehicle {
|
||||
除了它所继承的特性,`Bicycle`类还定义了一个默认值为`false`的存储型属性`hasBasket`(属性推断为`Bool`)。
|
||||
|
||||
默认情况下,你创建任何新的`Bicycle`实例将不会有一个篮子,创建该实例之后,你可以为特定的`Bicycle`实例设置`hasBasket `属性为`ture`:
|
||||
|
||||
|
||||
```swift
|
||||
let bicycle = Bicycle()
|
||||
bicycle.hasBasket = true
|
||||
```
|
||||
|
||||
|
||||
你还可以修改`Bicycle `实例所继承的`currentSpeed `属性,和查询实例所继承的`description `属性:
|
||||
|
||||
|
||||
```swift
|
||||
bicycle.currentSpeed = 15.0
|
||||
println("Bicycle: \(bicycle.description)")
|
||||
print("Bicycle: \(bicycle.description)")
|
||||
// Bicycle: traveling at 15.0 miles per hour
|
||||
```
|
||||
|
||||
@ -112,7 +112,7 @@ let tandem = Tandem()
|
||||
tandem.hasBasket = true
|
||||
tandem.currentNumberOfPassengers = 2
|
||||
tandem.currentSpeed = 22.0
|
||||
println("Tandem: \(tandem.description)")
|
||||
print("Tandem: \(tandem.description)")
|
||||
// Tandem: traveling at 22.0 miles per hour
|
||||
```
|
||||
|
||||
@ -144,7 +144,7 @@ println("Tandem: \(tandem.description)")
|
||||
```swift
|
||||
class Train: Vehicle {
|
||||
override func makeNoise() {
|
||||
println("Choo Choo")
|
||||
print("Choo Choo")
|
||||
}
|
||||
}
|
||||
```
|
||||
@ -189,7 +189,7 @@ class Car: Vehicle {
|
||||
let car = Car()
|
||||
car.currentSpeed = 25.0
|
||||
car.gear = 3
|
||||
println("Car: \(car.description)")
|
||||
print("Car: \(car.description)")
|
||||
// Car: traveling at 25.0 miles per hour in gear 3
|
||||
```
|
||||
|
||||
@ -217,7 +217,7 @@ class AutomaticCar: Car {
|
||||
```swift
|
||||
let automatic = AutomaticCar()
|
||||
automatic.currentSpeed = 35.0
|
||||
println("AutomaticCar: \(automatic.description)")
|
||||
print("AutomaticCar: \(automatic.description)")
|
||||
// AutomaticCar: traveling at 35.0 miles per hour in gear 4
|
||||
```
|
||||
|
||||
@ -229,4 +229,3 @@ println("AutomaticCar: \(automatic.description)")
|
||||
如果你重写了`final`方法,属性或下标脚本,在编译时会报错。在类扩展中的方法,属性或下标脚本也可以在扩展的定义里标记为 final。
|
||||
|
||||
你可以通过在关键字`class`前添加`final`特性(`final class`)来将整个类标记为 final 的,这样的类是不可被继承的,任何子类试图继承此类时,在编译时会报错。
|
||||
|
||||
|
||||
@ -13,7 +13,7 @@
|
||||
- [值类型的构造器代理](#initializer_delegation_for_value_types)
|
||||
- [类的继承和构造过程](#class_inheritance_and_initialization)
|
||||
- [可失败构造器](#failable_initializers)
|
||||
- [必要构造器](#required_initializers)
|
||||
- [必要构造器](#required_initializers)
|
||||
- [通过闭包和函数来设置属性的默认值](#setting_a_default_property_value_with_a_closure_or_function)
|
||||
|
||||
|
||||
@ -39,7 +39,7 @@
|
||||
|
||||
```swift
|
||||
init() {
|
||||
// 在此处执行构造过程
|
||||
// 在此处执行构造过程
|
||||
}
|
||||
```
|
||||
|
||||
@ -53,7 +53,7 @@ struct Fahrenheit {
|
||||
}
|
||||
}
|
||||
var f = Fahrenheit()
|
||||
println("The default temperature is \(f.temperature)° Fahrenheit")
|
||||
print("The default temperature is \(f.temperature)° Fahrenheit")
|
||||
// 输出 "The default temperature is 32.0° Fahrenheit”
|
||||
```
|
||||
|
||||
@ -182,7 +182,7 @@ class SurveyQuestion {
|
||||
self.text = text
|
||||
}
|
||||
func ask() {
|
||||
println(text)
|
||||
print(text)
|
||||
}
|
||||
}
|
||||
let cheeseQuestion = SurveyQuestion(text: "Do you like cheese?")
|
||||
@ -210,7 +210,7 @@ class SurveyQuestion {
|
||||
self.text = text
|
||||
}
|
||||
func ask() {
|
||||
println(text)
|
||||
print(text)
|
||||
}
|
||||
}
|
||||
let beetsQuestion = SurveyQuestion(text: "How about beets?")
|
||||
@ -656,7 +656,7 @@ var breakfastList = [
|
||||
breakfastList[0].name = "Orange juice"
|
||||
breakfastList[0].purchased = true
|
||||
for item in breakfastList {
|
||||
println(item.description)
|
||||
print(item.description)
|
||||
}
|
||||
// 1 x orange juice ✔
|
||||
// 1 x bacon ✘
|
||||
@ -666,13 +666,13 @@ for item in breakfastList {
|
||||
如上所述,例子中通过字面量方式创建了一个新数组`breakfastList`,它包含了三个新的`ShoppingListItem`实例,因此数组的类型也能自动推导为`ShoppingListItem[]`。在数组创建完之后,数组中第一个`ShoppingListItem`实例的名字从`[Unnamed]`修改为`Orange juice`,并标记为已购买。接下来通过遍历数组每个元素并打印它们的描述值,展示了所有项当前的默认状态都已按照预期完成了赋值。
|
||||
|
||||
<a name="failable_initializers"></a>
|
||||
## 可失败构造器
|
||||
## 可失败构造器
|
||||
|
||||
如果一个类,结构体或枚举类型的对象,在构造自身的过程中有可能失败,则为其定义一个可失败构造器,是非常有必要的。这里所指的“失败”是指,如给构造器传入无效的参数值,或缺少某种所需的外部资源,又或是不满足某种必要的条件等。
|
||||
|
||||
为了妥善处理这种构造过程中可能会失败的情况。你可以在一个类,结构体或是枚举类型的定义中,添加一个或多个可失败构造器。其语法为在`init`关键字后面加添问号`(init?)`。
|
||||
|
||||
> 注意:
|
||||
> 注意:
|
||||
可失败构造器的参数名和参数类型,不能与其它非可失败构造器的参数名,及其类型相同。
|
||||
|
||||
可失败构造器,在构建对象的过程中,创建一个其自身类型为可选类型的对象。你通过`return nil` 语句,来表明可失败构造器在何种情况下“失败”。
|
||||
@ -697,9 +697,9 @@ struct Animal {
|
||||
```swift
|
||||
let someCreature = Animal(species: "Giraffe")
|
||||
// someCreature 的类型是 Animal? 而不是 Animal
|
||||
|
||||
|
||||
if let giraffe = someCreature {
|
||||
println("An animal was initialized with a species of \(giraffe.species)")
|
||||
print("An animal was initialized with a species of \(giraffe.species)")
|
||||
}
|
||||
// 打印 "An animal was initialized with a species of Giraffe"
|
||||
```
|
||||
@ -709,9 +709,9 @@ if let giraffe = someCreature {
|
||||
```swift
|
||||
let anonymousCreature = Animal(species: "")
|
||||
// anonymousCreature 的类型是 Animal?, 而不是 Animal
|
||||
|
||||
|
||||
if anonymousCreature == nil {
|
||||
println("The anonymous creature could not be initialized")
|
||||
print("The anonymous creature could not be initialized")
|
||||
}
|
||||
// 打印 "The anonymous creature could not be initialized"
|
||||
```
|
||||
@ -748,13 +748,13 @@ enum TemperatureUnit {
|
||||
```swift
|
||||
let fahrenheitUnit = TemperatureUnit(symbol: "F")
|
||||
if fahrenheitUnit != nil {
|
||||
println("This is a defined temperature unit, so initialization succeeded.")
|
||||
print("This is a defined temperature unit, so initialization succeeded.")
|
||||
}
|
||||
// 打印 "This is a defined temperature unit, so initialization succeeded."
|
||||
|
||||
|
||||
let unknownUnit = TemperatureUnit(symbol: "X")
|
||||
if unknownUnit == nil {
|
||||
println("This is not a defined temperature unit, so initialization failed.")
|
||||
print("This is not a defined temperature unit, so initialization failed.")
|
||||
}
|
||||
// 打印 "This is not a defined temperature unit, so initialization failed."
|
||||
```
|
||||
@ -769,16 +769,16 @@ if unknownUnit == nil {
|
||||
enum TemperatureUnit: Character {
|
||||
case Kelvin = "K", Celsius = "C", Fahrenheit = "F"
|
||||
}
|
||||
|
||||
|
||||
let fahrenheitUnit = TemperatureUnit(rawValue: "F")
|
||||
if fahrenheitUnit != nil {
|
||||
println("This is a defined temperature unit, so initialization succeeded.")
|
||||
print("This is a defined temperature unit, so initialization succeeded.")
|
||||
}
|
||||
// prints "This is a defined temperature unit, so initialization succeeded."
|
||||
|
||||
|
||||
let unknownUnit = TemperatureUnit(rawValue: "X")
|
||||
if unknownUnit == nil {
|
||||
println("This is not a defined temperature unit, so initialization failed.")
|
||||
print("This is not a defined temperature unit, so initialization failed.")
|
||||
}
|
||||
// prints "This is not a defined temperature unit, so initialization failed."
|
||||
```
|
||||
@ -804,7 +804,7 @@ class Product {
|
||||
```swift
|
||||
if let bowTie = Product(name: "bow tie") {
|
||||
// 不需要检查 bowTie.name == nil
|
||||
println("The product's name is \(bowTie.name)")
|
||||
print("The product's name is \(bowTie.name)")
|
||||
}
|
||||
// 打印 "The product's name is bow tie"
|
||||
```
|
||||
@ -841,7 +841,7 @@ class CartItem: Product {
|
||||
|
||||
```swift
|
||||
if let twoSocks = CartItem(name: "sock", quantity: 2) {
|
||||
println("Item: \(twoSocks.name), quantity: \(twoSocks.quantity)")
|
||||
print("Item: \(twoSocks.name), quantity: \(twoSocks.quantity)")
|
||||
}
|
||||
// 打印 "Item: sock, quantity: 2"
|
||||
```
|
||||
@ -849,9 +849,9 @@ if let twoSocks = CartItem(name: "sock", quantity: 2) {
|
||||
|
||||
```swift
|
||||
if let zeroShirts = CartItem(name: "shirt", quantity: 0) {
|
||||
println("Item: \(zeroShirts.name), quantity: \(zeroShirts.quantity)")
|
||||
print("Item: \(zeroShirts.name), quantity: \(zeroShirts.quantity)")
|
||||
} else {
|
||||
println("Unable to initialize zero shirts")
|
||||
print("Unable to initialize zero shirts")
|
||||
}
|
||||
// 打印 "Unable to initialize zero shirts"
|
||||
```
|
||||
@ -860,9 +860,9 @@ if let zeroShirts = CartItem(name: "shirt", quantity: 0) {
|
||||
|
||||
```swift
|
||||
if let oneUnnamed = CartItem(name: "", quantity: 1) {
|
||||
println("Item: \(oneUnnamed.name), quantity: \(oneUnnamed.quantity)")
|
||||
print("Item: \(oneUnnamed.name), quantity: \(oneUnnamed.quantity)")
|
||||
} else {
|
||||
println("Unable to initialize one unnamed product")
|
||||
print("Unable to initialize one unnamed product")
|
||||
}
|
||||
// 打印 "Unable to initialize one unnamed product"
|
||||
```
|
||||
@ -920,7 +920,7 @@ class AutomaticallyNamedDocument: Document {
|
||||
你也可以用 ```init?```重写 ```init!```,反之亦然。
|
||||
你还可以用 ```init```代理调用```init!```,但这会触发一个断言:是否 ```init!```构造器会触发构造失败?
|
||||
|
||||
<a name="required_initializers"></a>
|
||||
<a name="required_initializers"></a>
|
||||
##必要构造器
|
||||
|
||||
在类的构造器前添加```required```修饰符表明所有该类的子类都必须实现该构造器:
|
||||
@ -1001,9 +1001,8 @@ struct Checkerboard {
|
||||
|
||||
```swift
|
||||
let board = Checkerboard()
|
||||
println(board.squareIsBlackAtRow(0, column: 1))
|
||||
print(board.squareIsBlackAtRow(0, column: 1))
|
||||
// 输出 "true"
|
||||
println(board.squareIsBlackAtRow(9, column: 9))
|
||||
print(board.squareIsBlackAtRow(9, column: 9))
|
||||
// 输出 "false"
|
||||
```
|
||||
|
||||
|
||||
@ -77,9 +77,9 @@ class Player {
|
||||
|
||||
```swift
|
||||
var playerOne: Player? = Player(coins: 100)
|
||||
println("A new player has joined the game with \(playerOne!.coinsInPurse) coins")
|
||||
print("A new player has joined the game with \(playerOne!.coinsInPurse) coins")
|
||||
// 输出 "A new player has joined the game with 100 coins"
|
||||
println("There are now \(Bank.coinsInBank) coins left in the bank")
|
||||
print("There are now \(Bank.coinsInBank) coins left in the bank")
|
||||
// 输出 "There are now 9900 coins left in the bank"
|
||||
```
|
||||
|
||||
@ -89,9 +89,9 @@ println("There are now \(Bank.coinsInBank) coins left in the bank")
|
||||
|
||||
```swift
|
||||
playerOne!.winCoins(2_000)
|
||||
println("PlayerOne won 2000 coins & now has \(playerOne!.coinsInPurse) coins")
|
||||
print("PlayerOne won 2000 coins & now has \(playerOne!.coinsInPurse) coins")
|
||||
// 输出 "PlayerOne won 2000 coins & now has 2100 coins"
|
||||
println("The bank now only has \(Bank.coinsInBank) coins left")
|
||||
print("The bank now only has \(Bank.coinsInBank) coins left")
|
||||
// 输出 "The bank now only has 7900 coins left"
|
||||
```
|
||||
|
||||
@ -99,9 +99,9 @@ println("The bank now only has \(Bank.coinsInBank) coins left")
|
||||
|
||||
```swift
|
||||
playerOne = nil
|
||||
println("PlayerOne has left the game")
|
||||
print("PlayerOne has left the game")
|
||||
// 输出 "PlayerOne has left the game"
|
||||
println("The bank now has \(Bank.coinsInBank) coins")
|
||||
print("The bank now has \(Bank.coinsInBank) coins")
|
||||
// 输出 "The bank now has 10000 coins"
|
||||
```
|
||||
|
||||
|
||||
@ -299,7 +299,7 @@ class CreditCard {
|
||||
}
|
||||
```
|
||||
|
||||
> 注意:
|
||||
> 注意:
|
||||
> `CreditCard`类的`number`属性被定义为`UInt64`类型而不是`Int`类型,以确保`number`属性的存储量在32位和64位系统上都能足够容纳16位的卡号。
|
||||
|
||||
下面的代码片段定义了一个叫`john`的可选类型`Customer`变量,用来保存某个特定客户的引用。由于是可选类型,所以变量被初始化为`nil`。
|
||||
@ -557,4 +557,3 @@ print(paragraph!.asHTML())
|
||||
paragraph = nil
|
||||
// prints "p is being deinitialized"
|
||||
```
|
||||
|
||||
|
||||
@ -62,9 +62,9 @@ let roomCount = john.residence!.numberOfRooms
|
||||
|
||||
```swift
|
||||
if let roomCount = john.residence?.numberOfRooms {
|
||||
println("John's residence has \(roomCount) room(s).")
|
||||
print("John's residence has \(roomCount) room(s).")
|
||||
} else {
|
||||
println("Unable to retrieve the number of rooms.")
|
||||
print("Unable to retrieve the number of rooms.")
|
||||
}
|
||||
// 打印 "Unable to retrieve the number of rooms.
|
||||
```
|
||||
@ -85,9 +85,9 @@ john.residence = Residence()
|
||||
|
||||
```swift
|
||||
if let roomCount = john.residence?.numberOfRooms {
|
||||
println("John's residence has \(roomCount) room(s).")
|
||||
print("John's residence has \(roomCount) room(s).")
|
||||
} else {
|
||||
println("Unable to retrieve the number of rooms.")
|
||||
print("Unable to retrieve the number of rooms.")
|
||||
}
|
||||
// 打印 "John's residence has 1 room(s)"。
|
||||
```
|
||||
@ -119,7 +119,7 @@ class Residence {
|
||||
return rooms[i]
|
||||
}
|
||||
func printNumberOfRooms() {
|
||||
println("The number of rooms is \(numberOfRooms)")
|
||||
print("The number of rooms is \(numberOfRooms)")
|
||||
}
|
||||
var address: Address?
|
||||
}
|
||||
@ -173,9 +173,9 @@ class Address {
|
||||
```swift
|
||||
let john = Person()
|
||||
if let roomCount = john.residence?.numberOfRooms {
|
||||
println("John's residence has \(roomCount) room(s).")
|
||||
print("John's residence has \(roomCount) room(s).")
|
||||
} else {
|
||||
println("Unable to retrieve the number of rooms.")
|
||||
print("Unable to retrieve the number of rooms.")
|
||||
}
|
||||
// 打印 "Unable to retrieve the number of rooms。
|
||||
```
|
||||
@ -191,7 +191,7 @@ if let roomCount = john.residence?.numberOfRooms {
|
||||
|
||||
```swift
|
||||
func printNumberOfRooms(){
|
||||
println(“The number of rooms is \(numberOfRooms)”)
|
||||
print(“The number of rooms is \(numberOfRooms)”)
|
||||
}
|
||||
```
|
||||
|
||||
@ -201,9 +201,9 @@ func printNumberOfRooms(){
|
||||
|
||||
```swift
|
||||
if john.residence?.printNumberOfRooms?() {
|
||||
println("It was possible to print the number of rooms.")
|
||||
print("It was possible to print the number of rooms.")
|
||||
} else {
|
||||
println("It was not possible to print the number of rooms.")
|
||||
print("It was not possible to print the number of rooms.")
|
||||
}
|
||||
// 打印 "It was not possible to print the number of rooms."。
|
||||
```
|
||||
@ -220,9 +220,9 @@ if john.residence?.printNumberOfRooms?() {
|
||||
|
||||
```swift
|
||||
if let firstRoomName = john.residence?[0].name {
|
||||
println("The first room name is \(firstRoomName).")
|
||||
print("The first room name is \(firstRoomName).")
|
||||
} else {
|
||||
println("Unable to retrieve the first room name.")
|
||||
print("Unable to retrieve the first room name.")
|
||||
}
|
||||
// 打印 "Unable to retrieve the first room name."。
|
||||
```
|
||||
@ -238,9 +238,9 @@ johnsHouse.rooms += Room(name: "Kitchen")
|
||||
john.residence = johnsHouse
|
||||
|
||||
if let firstRoomName = john.residence?[0].name {
|
||||
println("The first room name is \(firstRoomName).")
|
||||
print("The first room name is \(firstRoomName).")
|
||||
} else {
|
||||
println("Unable to retrieve the first room name.")
|
||||
print("Unable to retrieve the first room name.")
|
||||
}
|
||||
// 打印 "The first room name is Living Room."。
|
||||
```
|
||||
@ -263,9 +263,9 @@ if let firstRoomName = john.residence?[0].name {
|
||||
|
||||
```swift
|
||||
if let johnsStreet = john.residence?.address?.street {
|
||||
println("John's street name is \(johnsStreet).")
|
||||
print("John's street name is \(johnsStreet).")
|
||||
} else {
|
||||
println("Unable to retrieve the address.")
|
||||
print("Unable to retrieve the address.")
|
||||
}
|
||||
// 打印 "Unable to retrieve the address.”。
|
||||
```
|
||||
@ -285,9 +285,9 @@ john.residence!.address = johnsAddress
|
||||
|
||||
```swift
|
||||
if let johnsStreet = john.residence?.address?.street {
|
||||
println("John's street name is \(johnsStreet).")
|
||||
print("John's street name is \(johnsStreet).")
|
||||
} else {
|
||||
println("Unable to retrieve the address.")
|
||||
print("Unable to retrieve the address.")
|
||||
}
|
||||
// 打印 "John's street name is Laurel Street."。
|
||||
```
|
||||
@ -303,7 +303,7 @@ if let johnsStreet = john.residence?.address?.street {
|
||||
|
||||
```swift
|
||||
if let buildingIdentifier = john.residence?.address?.buildingIdentifier() {
|
||||
println("John's building identifier is \(buildingIdentifier).")
|
||||
print("John's building identifier is \(buildingIdentifier).")
|
||||
}
|
||||
// 打印 "John's building identifier is The Larches."。
|
||||
```
|
||||
@ -312,7 +312,7 @@ if let buildingIdentifier = john.residence?.address?.buildingIdentifier() {
|
||||
|
||||
```swift
|
||||
if let upper = john.residence?.address?.buildingIdentifier()?.uppercaseString {
|
||||
println("John's uppercase building identifier is \(upper).")
|
||||
print("John's uppercase building identifier is \(upper).")
|
||||
}
|
||||
// 打印 "John's uppercase building identifier is THE LARCHES."。
|
||||
```
|
||||
|
||||
@ -45,7 +45,7 @@ struct BlackjackCard {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// BlackjackCard 的属性和方法
|
||||
let rank: Rank, suit: Suit
|
||||
var description: String {
|
||||
@ -93,4 +93,3 @@ let heartsSymbol = BlackjackCard.Suit.Hearts.rawValue
|
||||
```
|
||||
|
||||
对于上面这个例子,这样可以使`Suit`, `Rank`, 和 `Values`的名字尽可能的短,因为它们的名字会自然的由定义它们的上下文来限定。
|
||||
|
||||
|
||||
@ -67,10 +67,10 @@ extension Double {
|
||||
var ft: Double { return self / 3.28084 }
|
||||
}
|
||||
let oneInch = 25.4.mm
|
||||
println("One inch is \(oneInch) meters")
|
||||
print("One inch is \(oneInch) meters")
|
||||
// 打印输出:"One inch is 0.0254 meters"
|
||||
let threeFeet = 3.ft
|
||||
println("Three feet is \(threeFeet) meters")
|
||||
print("Three feet is \(threeFeet) meters")
|
||||
// 打印输出:"Three feet is 0.914399970739201 meters"
|
||||
```
|
||||
|
||||
@ -84,7 +84,7 @@ println("Three feet is \(threeFeet) meters")
|
||||
|
||||
```swift
|
||||
let aMarathon = 42.km + 195.m
|
||||
println("A marathon is \(aMarathon) meters long")
|
||||
print("A marathon is \(aMarathon) meters long")
|
||||
// 打印输出:"A marathon is 42195.0 meters long"
|
||||
```
|
||||
|
||||
@ -169,7 +169,7 @@ extension Int {
|
||||
|
||||
```swift
|
||||
3.repetitions({
|
||||
println("Hello!")
|
||||
print("Hello!")
|
||||
})
|
||||
// Hello!
|
||||
// Hello!
|
||||
@ -180,7 +180,7 @@ extension Int {
|
||||
|
||||
```swift
|
||||
3.repetitions{
|
||||
println("Goodbye!")
|
||||
print("Goodbye!")
|
||||
}
|
||||
// Goodbye!
|
||||
// Goodbye!
|
||||
@ -296,5 +296,3 @@ printIntegerKinds([3, 19, -27, 0, -6, 0, 7])
|
||||
|
||||
>注意:
|
||||
由于已知`number.kind `是`Int.Kind`型,所以`Int.Kind`中的所有成员值都可以使用`switch`语句里的形式简写,比如使用 `. Negative`代替`Int.Kind.Negative`。
|
||||
|
||||
|
||||
|
||||
@ -255,7 +255,7 @@ struct TrackedString {
|
||||
```
|
||||
|
||||
|
||||
`TrackedString`结构体定义了一个用于存储`String`类型的属性`value`,并将初始化值设为`""`(即一个空字符串)。该结构体同时也定义了另一个用于存储`Int`类型的属性名`numberOfEdits`,它用于记录属性`value`被修改的次数。这个功能的实现通过属性`value`的`didSet`方法实现,每当给`value`赋新值时就会调用`didSet`方法,然后将`numberOfEdits`的值加一。
|
||||
`TrackedString`结构体定义了一个用于存储`String`类型的属性`value`,并将初始化值设为`""`(即一个空字符串)。该结构体同时也定义了另一个用于存储`Int`类型的属性名`numberOfEdits`,它用于记录属性`value`被修改的次数。这个功能的实现通过属性`value`的`didSet`方法实现,每当给`value`赋新值时就会调用`didSet`方法,然后将`numberOfEdits`的值加一。
|
||||
|
||||
结构体`TrackedString`和它的属性`value`均没有申明显式访问级别,所以它们都拥有默认的访问级别`internal`。但是该结构体的`numberOfEdits`属性使用`private(set)`修饰符进行申明,这意味着`numberOfEdits`属性只能在定义该结构体的源文件中赋值。`numberOfEdits`属性的`Getter`依然是默认的访问级别`internal`,但是`Setter`的访问级别是`private`,这表示该属性只有在当前的源文件中是可读写的,而在当前源文件所属的模块中它只是一个可读的属性。
|
||||
|
||||
@ -266,7 +266,7 @@ var stringToEdit = TrackedString()
|
||||
stringToEdit.value = "This string will be tracked."
|
||||
stringToEdit.value += " This edit will increment numberOfEdits."
|
||||
stringToEdit.value += " So will this one."
|
||||
println("The number of edits is \(stringToEdit.numberOfEdits)")
|
||||
print("The number of edits is \(stringToEdit.numberOfEdits)")
|
||||
// prints "The number of edits is 3"
|
||||
```
|
||||
|
||||
@ -345,6 +345,3 @@ Swift为结构体、类都提供了一个默认的无参初始化方法,用于
|
||||
任何你定义的类型别名都会被当作不同的类型,以便于进行访问控制。一个类型别名的访问级别不可高于原类型的访问级别。比如说,一个`private`级别的类型别名可以设定给一个`public`、`internal`、`private`的类型,但是一个`public`级别的类型别名只能设定给一个`public`级别的类型,不能设定给`internal`或`private` 级别的类型。
|
||||
|
||||
> 注意:这条规则也适用于为满足协议一致性而给相关类型命名别名的情况。
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user