This commit is contained in:
Zhang Honghao
2014-06-04 18:23:55 -04:00
15 changed files with 1590 additions and 52 deletions

View File

@ -20,6 +20,7 @@
- 帮忙一起翻译
- 帮忙校对,挑错别字、病句等等
- 提出修改建议
- 提出术语翻译建议
# 翻译建议
@ -30,10 +31,19 @@
- 工作分支为gh-pages用于GitHub的pages服务
- fork过去之后新建一个分支进行翻译完成后pull request这个分支没问题的话我会合并到gh-pages分支中
- 有其他任何问题都欢迎发issue我看到了会尽快回复
- **尽早pull request**你不必翻译完整篇文章再pr完全可以翻译完一段就pr一次这样别的朋友可以及时看到你的进度避免多人翻译同一段。此外尽早pr也可以让校对的朋友们更早看到新内容更快发现问题
- **尽早pull request**你不必翻译完整篇文章再pr完全可以翻译完一段就pr一次这样别的朋友可以及时看到你的进度避免多人翻译同一段。此外尽早pr也可以让校对的朋友们更早看到新内容更快发现问题
- 一定要记得**先查看当前的pr**再开始翻译,防止重复翻译
谢谢!
# 关于术语
翻译术语的时候请参考这个流程:
- 尽量保证和已翻译的内容一致
- 尽量先搜索,一般来说编程语言的大部分术语是一样的,可以参考[微软官方术语搜索](http://www.microsoft.com/Language/zh-cn/Search.aspx)
- 如果以上两条都没有找到合适的结果,请自己决定一个合适的翻译或者直接使用英文原文,后期校对的时候会进行统一
# 参考流程
有些朋友可能不太清楚如何帮忙翻译,我这里写一个简单的流程,大家可以参考一下:

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

View File

@ -0,0 +1,234 @@
--- [@haolloyin](https://github.com/haolloyin) 翻译自苹果官方文档 [Using Swift with Cocoa and Objective-C](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html#//apple_ref/doc/uid/TP40014216-CH10-XID_75) 的 [Mix and Match](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html) 章节
# Swift and Objective-C in the Same Project - 在同个工程中使用 Swift 和 Objc
Swift 与 Objc 的兼容能力使你可以在同一个工程中同时使用两种语言。你可以用这种叫做 `mix and match` 的特性来开发基于混合语言的应用,可以用 Swfit 的最新特性实现应用的一部分功能,并无缝地并入已有的 Objc 的代码中。
## Mix and Match 概述
Objc 和 Swift 文件可以在一个工程中并存,不管这个工程原本是基于 Objc 还是 Swift。你可以直接往现有工程中简单地添加另一种语言的源文件。这种自然的工作流使得创建混合语言的应用或框架 target与用单独一种语言时一样简单。
混合语言的工作流程只有一点点区别,这取决于你是在写应用还是写框架。下面描述了普通的用两种语言在一个 target 中导入模型的情况,后续章节会有更多细节。
![DAG_2x.png](https://raw.githubusercontent.com/haolloyin/the-swift-programming-language-in-chinese/translate/Using%20Swift%20with%20Cocoa%20and%20ObjectiveC/chapter3/DAG_2x.png?raw=true)
## Importing Code from Within the Same App Target - 在同个应用的 target 中导入
如果你在写混合语言的应用,可能需要用 Swift 代码访问 Objc 代码,或者反之。下面的流程描述了在非框架 target 中的应用。
### Importing Objective-C into Swift - 将 Objc 导入 Swift
在一个应用的 target 中导入一些 Objc 文件供 Swift 代码使用时,你需要依赖与 Objc 的桥接头文件(`bridging header`)来暴露给 Swift。当你添加 Swift 文件到现有的 Objc 应用或反之Xcode 会自动创建这些头文件。
![bridgingheader_2x.png](https://raw.githubusercontent.com/haolloyin/the-swift-programming-language-in-chinese/translate/Using%20Swift%20with%20Cocoa%20and%20ObjectiveC/chapter3/bridgingheader_2x.png?raw=true)
如果你同意Xcode 会在源文件创建的同时生成头文件,并用 product 的模块名加上 `-Bridging-Header.h` 命名。关于 product 的模块名,详见 [Naming Your Product Module](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html#//apple_ref/doc/uid/TP40014216-CH10-XID_85)。
你应该编辑这个头文件来对 Swift 暴露出 Objc 代码。
##### To import Objective-C code into Swift from the same target
1.在 Objc 桥接头文件中import 任何你想暴露给 Swift 的头文件,例如:
```
// OBJECTIVE-C
#import "XYZCustomCell.h"
#import "XYZCustomView.h"
#import "XYZCustomViewController.h"
```
2.确保在 `Build Settings` 中 Objc 桥接头文件的 `build setting` 是基于 Swfit 编译器,即 `Code Generation` 含有头文件的路径。这个路径必须是头文件自身的路径,而不是它所在的目录。
这个路径应该是你工程的相对路径,类似 `Info.plist``Build Settings` 中指定的路径。在大多数情况下,你不需要修改这个设置。
在这个桥接头文件中列出的所有 public 的 Objc 头文件都会对 Swift 可见。之后当前 target 的所有 Swift 文件都可以使用这些头文件中的方法,不需要任何 import 语句。用 Swift 语法使用这些 Objc 代码,就像使用系统自带的 Swift 类一样。
```
// SWIFT
let myCell = XYZCustomCell()
myCell.subtitle = "A custom cell"
```
### Importing Swift into Objective-C - 将 Swift 导入 Objc
向 Objc 中导入Swift 代码时,你依赖 Xcode 生成的头文件来向 Objc 暴露 Swift 代码。这是自动生成 Objc 头文件,它包含了你的 target 中所有 Swift 代码中定义的接口。可以把这个 Objc 头文件看作 Swift 代码的 `umbrella header`。它以 product 模块名加 `-Swift.h` 来命名。关于 product 的模块名,详见 [Naming Your Product Module](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html#//apple_ref/doc/uid/TP40014216-CH10-XID_85)。
你不需要做任何事情来生成这个头文件,只需要将它导入到你的 Objc 代码来使用它。注意这个头文件中的 Swift 接口包含了它所使用到的所有 Objc 类型。如果你在 Swift 代码中使用你自己的 Objc 类型,确保先将对应的 Objc 头文件导入到你的 Swift 代码中,然后才将 Swift 自动生成的头文件导入到 Objc .m 源文件中来访问 Swift 代码。
##### To import Swift code into Objective-C from the same target
- 在相同 target 的 Objc .m 源文件中用下面的语法来导入Swift 代码:
```
// OBJECTIVE-C
#import "ProductModuleName-Swift.h"
```
target 中任何 Swift 文件将会对 Objc .m 源文件可见,包括这个 import 语句。关于在 Objc 代码中使用 Swift 代码,详见 [Using Swift from Objective-C](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html#//apple_ref/doc/uid/TP40014216-CH10-XID_84)。
| 导入到 Swift | 导入到 Objc
---------- | ---------- | ----------
Swift 代码 | 不需要import语句 | #import <ProductName/ProductModuleName-Swift.h>
Objc 代码 | 不需要import语句需要 Objc `umbrella头文件` | #import "Header.h"
## Importing Code from Within the Same Framework Target - 在同个 Framework 的 target 中导入
如果你在写一个混合语言的框架,可能会从 Swift 代码访问 Objc 代码,或者反之。
### Importing Objective-C into Swift - 将 Objc 导入 Swift
要将一些 Objc 文件导入到同个框架 target 的 Swift 代码中去,你需要将这些文件导入到 Objc 的 `umbrella header` 来供框架使用。
##### To import Objective-C code into Swift from the same framework
确保将框架 target 的 `Build Settings > Packaging > Defines Module` 设置为 `Yes`。然后在你的 `umbrella header` 头文件中导入你想暴露给 Swift 访问的 Objc 头文件,例如:
```
// OBJECTIVE-C
#import <XYZ/XYZCustomCell.h>
#import <XYZ/XYZCustomView.h>
#import <XYZ/XYZCustomViewController.h>
```
Swift 将会看到所有你在 `umbrella header` 中公开暴露出来的头文件,框架 target 中的所有 Swift 文件都可以访问你 Objc 文件的内容,不需要任何 import 语句。
```
// SWIFT
let myCell = XYZCustomCell()
myCell.subtitle = "A custom cell"
```
### Importing Swift into Objective-C - 将 Swift 导入 Objc
要将一些 Swift 文件导入到同个框架的 target 的 Objc 代码去,你不需要导入任何东西到 `umbrella header` 文件,而是将 Xcode 为你的 Swift 代码自动生成的头文件导入到你的 Obj .m 源文件去,以便在 Objc 代码中访问 Swift 代码。
##### To import Swift code into Objective-C from the same framework
确保将框架 target 的 `Build Settings > Packaging` 中的 `Defines Module` 设置为 `Yes`。用下面的语法将 Swift 代码导入到同个框架 target 下的 Objc .m 源文件去。
```
// OBJECTIVE-C
#import <ProductName/ProductModuleName-Swift.h>
```
这个 import 语句所包含的 Swift 文件都可以被同个框架 target 下的 Objc .m 源文件访问。关于在 Objc 代码中使用 Swift 代码,详见 [Using Swift from Objective-C](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html#//apple_ref/doc/uid/TP40014216-CH10-XID_84)。
| 导入到 Swift | 导入到 Objc
---------- | ---------- | ----------
Swift 代码 | 不需要import语句 | #import <ProductName/ProductModuleName-Swift.h>
Objc 代码 | 不需要import语句需要 Objc `umbrella头文件` | #import "Header.h"
## Importing External Frameworks - 导入外部 Framework
你可以导入外部框架,不管这个框架是纯 Objc纯 Swift还是混合语言的。import 外部框架的流程都是一样的,不管这个框架是用一种语言写的,还是包含两种语言。当你导入外部框架时,确保 `Build Setting > Pakaging > Defines Module` 设置为 `Yes`
用下面的语法将框架导入到不同 target 的 Swift 文件中:
```
// SWIFT
import FrameworkName
```
用下面的语法将框架导入到不同 target 的 Objc .m 文件中:
```
OBJECTIVE-C
@import FrameworkName;
```
Import into Swift
Import into Objective-C
Any language framework
import FrameworkName
@import FrameworkName;
## Using Swift from Objective-C - 在 Objc 中使用 Swift
当你将 Swift 代码导入 Objc 文件之后,用普通的 Objc 语法使用 Swift 类。
```
// OBJECTIVE-C
MySwiftClass *swiftObject = [[MySwiftClass alloc] init];
[swiftObject swiftMethod];
```
Swift 的类或协议必须用 `@objc attribute` 来标记,以便在 Objc 中可访问。这个 attribute 告诉编译器这个 Swift 代码可以从 Objc 代码中访问。如果你的 Swift 类是 Objc 类的子类,编译器会自动为你添加 `@objc attribute`。详见 [Swift Type Compatibility](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/InteractingWithObjective-CAPIs.html#//apple_ref/doc/uid/TP40014216-CH4-XID_36)。
你可以访问 Swift 类或协议中用 `@objc attribute` 标记过东西,只要它和 Objc 兼容。不包括一下这些 Swift 独有的特性:
Generics - 范型
Tuples - 元组
Enumerations defined in Swift - Swift 中定义的枚举
Structures defined in Swift - Swift 中定义的结构体
Top-level functions defined in Swift - Swift Swift 中定义的顶层函数
Global variables defined in Swift - Swift 中定义的全局变量
Typealiases defined in Swift - Swift 中定义的类型别名
Swift-style variadics
Nested types - 嵌套类型
Curried functions - 柯里化后的函数
例如带有范型类型作为参数,或者返回元组的方法不能在 Objc 中使用。
为了避免循环引用,不要将 Swift 代码导入到 Objc 头文件中。但是你可以在 Objc 头文件中前向声明(`forward declare`)一个 Swift 类来使用它,然而,注意**不能在 Objc 中继承一个 Swift 类。**
### To reference a Swift class in an Objective-C header file
这样前向声明 Swift 类:
```
// OBJECTIVE-C
// MyObjcClass.h
@class MySwiftClass;
@interface MyObjcClass : NSObject
- (MySwiftClass *)returnSwiftObject;
/* ... */
@end
```
## Naming Your Product Module - Product 模块命名
Xcode 为 Swift 代码生成的头文件的名称,以及 Xcode 创建的 Objc 桥接头文件名称,都是从你的 product 模块名生成的。默认你的 product 模块名和 product 名一样。然而,如果你的 product 名有特殊字符nonalphanumeric非数字、字母的字符例如点号那么它们会被下划线`_`)替换之后作为你的 product 模块名。如果 product 名以数字开头,那么第一个数字会用下划线替换掉。
你可以给 product 模块名提供一个自定义的名称Xcode 会用这个名称来命名桥接的和自动生成的头文件。你只需要在修改在 `build setting` 中的 `Product Module Name` 即可。
## Troubleshooting Tips and Reminders
- 把 Swift 和 Objc 文件看作相同的代码集合,并注意命名冲突;
- 如果你用框架,确保 `Build Setting > Pakaging > Defines Module` 设置为 `Yes`
- 如果你使用 Objc 桥接头文件,确保在 `Build Settings` 中 Objc 桥接头文件的 `build setting` 是基于 Swfit 编译器,即 `Code Generation` 含有头文件的路径。这个路径必须是头文件自身的路径,而不是它所在的目录。
- Xcode 使用你的 product 模块名,而不是 target 名来命名 Objc 桥接头文件和为 Swift 自动生成的头文件。详见 [Naming Your Product Module](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html#//apple_ref/doc/uid/TP40014216-CH10-XID_85)
- 为了在 Objc 中可用, Swift 类必须是 Objc 类的子类,或者用 `@objc` 标记;
- 当你将 Swift 导入到 Objc 中时,记住 Objc 不会将 Swift 独有的特性翻译成 Objc 对应的特性。详见列表 [Using Swift from Objective-C](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html#//apple_ref/doc/uid/TP40014216-CH10-XID_84);
- 如果你在 Swift 代码中使用你自己的 Objc 类型,确保先将对应的 Objc 头文件导入到你的 Swift 代码中,然后才将 Swift 自动生成的头文件 import 到 Objc .m 源文件中来访问 Swift 代码。

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

View File

@ -46,7 +46,7 @@
<div class="book" data-level="1" data-basepath=".." data-revision="1401895096940">
<div class="book" data-level="1" data-basepath=".." data-revision="1401919801865">
<div class="book-header">
<!-- Actions Left -->
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
@ -173,6 +173,24 @@
</a>
</li>
<li class="chapter " data-level="2.2" data-path="chapter2/basic_operators.html">
<a href="../chapter2/basic_operators.html">
<i class="fa fa-check"></i> <b>2.2.</b> 基本操作符
</a>
</li>
<li class="chapter " data-level="2.3" data-path="chapter2/strings_and_characters.html">
<a href="../chapter2/strings_and_characters.html">
<i class="fa fa-check"></i> <b>2.3.</b> 字符串和字符
</a>
</li>
@ -197,28 +215,32 @@
<div class="page-wrapper" tabindex="-1">
<div class="book-progress">
<div class="bar">
<div class="inner" style="width: 20%;min-width: 0%;"></div>
<div class="inner" style="width: 14.285714285714286%;min-width: 0%;"></div>
</div>
<div class="chapters">
<a href="../index.html" title="Introduction" class="chapter done new-chapter" data-progress="0" style="left: 0%;"></a>
<a href="../chapter1/README.html" title="欢迎使用 Swift" class="chapter done new-chapter" data-progress="1" style="left: 20%;"></a>
<a href="../chapter1/README.html" title="欢迎使用 Swift" class="chapter done new-chapter" data-progress="1" style="left: 14.285714285714286%;"></a>
<a href="../chapter1/swift.html" title="关于 Swift" class="chapter " data-progress="1.1" style="left: 40%;"></a>
<a href="../chapter1/swift.html" title="关于 Swift" class="chapter " data-progress="1.1" style="left: 28.571428571428573%;"></a>
<a href="../chapter1/a_swift_tour.html" title="Swift 初见" class="chapter " data-progress="1.2" style="left: 60%;"></a>
<a href="../chapter1/a_swift_tour.html" title="Swift 初见" class="chapter " data-progress="1.2" style="left: 42.857142857142854%;"></a>
<a href="../chapter2/the_basics.html" title="Swift 教程" class="chapter new-chapter" data-progress="2" style="left: 80%;"></a>
<a href="../chapter2/the_basics.html" title="Swift 教程" class="chapter new-chapter" data-progress="2" style="left: 57.142857142857146%;"></a>
<a href="../chapter2/article_1.html" title="基础部分" class="chapter " data-progress="2.1" style="left: 100%;"></a>
<a href="../chapter2/article_1.html" title="基础部分" class="chapter " data-progress="2.1" style="left: 71.42857142857143%;"></a>
<a href="../chapter2/basic_operators.html" title="基本操作符" class="chapter " data-progress="2.2" style="left: 85.71428571428571%;"></a>
<a href="../chapter2/strings_and_characters.html" title="字符串和字符" class="chapter " data-progress="2.3" style="left: 100%;"></a>
</div>
</div>
<div class="page-inner">
<section class="normal" id="section-gitbook_13">
<section class="normal" id="section-gitbook_6">
<h1 id="-swift">欢迎使用 Swift</h1>
<p>在本章中您将了解 Swift 的特性和开发历史,并对 Swift 有一个初步的了解。</p>

View File

@ -46,7 +46,7 @@
<div class="book" data-level="1.2" data-basepath=".." data-revision="1401895096940">
<div class="book" data-level="1.2" data-basepath=".." data-revision="1401919801865">
<div class="book-header">
<!-- Actions Left -->
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
@ -173,6 +173,24 @@
</a>
</li>
<li class="chapter " data-level="2.2" data-path="chapter2/basic_operators.html">
<a href="../chapter2/basic_operators.html">
<i class="fa fa-check"></i> <b>2.2.</b> 基本操作符
</a>
</li>
<li class="chapter " data-level="2.3" data-path="chapter2/strings_and_characters.html">
<a href="../chapter2/strings_and_characters.html">
<i class="fa fa-check"></i> <b>2.3.</b> 字符串和字符
</a>
</li>
@ -197,28 +215,32 @@
<div class="page-wrapper" tabindex="-1">
<div class="book-progress">
<div class="bar">
<div class="inner" style="width: 60%;min-width: 40%;"></div>
<div class="inner" style="width: 42.857142857142854%;min-width: 28.571428571428573%;"></div>
</div>
<div class="chapters">
<a href="../index.html" title="Introduction" class="chapter done new-chapter" data-progress="0" style="left: 0%;"></a>
<a href="../chapter1/README.html" title="欢迎使用 Swift" class="chapter done new-chapter" data-progress="1" style="left: 20%;"></a>
<a href="../chapter1/README.html" title="欢迎使用 Swift" class="chapter done new-chapter" data-progress="1" style="left: 14.285714285714286%;"></a>
<a href="../chapter1/swift.html" title="关于 Swift" class="chapter done " data-progress="1.1" style="left: 40%;"></a>
<a href="../chapter1/swift.html" title="关于 Swift" class="chapter done " data-progress="1.1" style="left: 28.571428571428573%;"></a>
<a href="../chapter1/a_swift_tour.html" title="Swift 初见" class="chapter done " data-progress="1.2" style="left: 60%;"></a>
<a href="../chapter1/a_swift_tour.html" title="Swift 初见" class="chapter done " data-progress="1.2" style="left: 42.857142857142854%;"></a>
<a href="../chapter2/the_basics.html" title="Swift 教程" class="chapter new-chapter" data-progress="2" style="left: 80%;"></a>
<a href="../chapter2/the_basics.html" title="Swift 教程" class="chapter new-chapter" data-progress="2" style="left: 57.142857142857146%;"></a>
<a href="../chapter2/article_1.html" title="基础部分" class="chapter " data-progress="2.1" style="left: 100%;"></a>
<a href="../chapter2/article_1.html" title="基础部分" class="chapter " data-progress="2.1" style="left: 71.42857142857143%;"></a>
<a href="../chapter2/basic_operators.html" title="基本操作符" class="chapter " data-progress="2.2" style="left: 85.71428571428571%;"></a>
<a href="../chapter2/strings_and_characters.html" title="字符串和字符" class="chapter " data-progress="2.3" style="left: 100%;"></a>
</div>
</div>
<div class="page-inner">
<section class="normal" id="section-gitbook_14">
<section class="normal" id="section-gitbook_7">
<h1 id="swift-">Swift 初见</h1>
<p>通常来说编程语言教程中的第一个程序应该在屏幕上打印“Hello, world”。在 Swift 中,可以用一行代码实现:</p>

View File

@ -46,7 +46,7 @@
<div class="book" data-level="1.1" data-basepath=".." data-revision="1401895096940">
<div class="book" data-level="1.1" data-basepath=".." data-revision="1401919801865">
<div class="book-header">
<!-- Actions Left -->
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
@ -173,6 +173,24 @@
</a>
</li>
<li class="chapter " data-level="2.2" data-path="chapter2/basic_operators.html">
<a href="../chapter2/basic_operators.html">
<i class="fa fa-check"></i> <b>2.2.</b> 基本操作符
</a>
</li>
<li class="chapter " data-level="2.3" data-path="chapter2/strings_and_characters.html">
<a href="../chapter2/strings_and_characters.html">
<i class="fa fa-check"></i> <b>2.3.</b> 字符串和字符
</a>
</li>
@ -197,28 +215,32 @@
<div class="page-wrapper" tabindex="-1">
<div class="book-progress">
<div class="bar">
<div class="inner" style="width: 40%;min-width: 20%;"></div>
<div class="inner" style="width: 28.571428571428573%;min-width: 14.285714285714286%;"></div>
</div>
<div class="chapters">
<a href="../index.html" title="Introduction" class="chapter done new-chapter" data-progress="0" style="left: 0%;"></a>
<a href="../chapter1/README.html" title="欢迎使用 Swift" class="chapter done new-chapter" data-progress="1" style="left: 20%;"></a>
<a href="../chapter1/README.html" title="欢迎使用 Swift" class="chapter done new-chapter" data-progress="1" style="left: 14.285714285714286%;"></a>
<a href="../chapter1/swift.html" title="关于 Swift" class="chapter done " data-progress="1.1" style="left: 40%;"></a>
<a href="../chapter1/swift.html" title="关于 Swift" class="chapter done " data-progress="1.1" style="left: 28.571428571428573%;"></a>
<a href="../chapter1/a_swift_tour.html" title="Swift 初见" class="chapter " data-progress="1.2" style="left: 60%;"></a>
<a href="../chapter1/a_swift_tour.html" title="Swift 初见" class="chapter " data-progress="1.2" style="left: 42.857142857142854%;"></a>
<a href="../chapter2/the_basics.html" title="Swift 教程" class="chapter new-chapter" data-progress="2" style="left: 80%;"></a>
<a href="../chapter2/the_basics.html" title="Swift 教程" class="chapter new-chapter" data-progress="2" style="left: 57.142857142857146%;"></a>
<a href="../chapter2/article_1.html" title="基础部分" class="chapter " data-progress="2.1" style="left: 100%;"></a>
<a href="../chapter2/article_1.html" title="基础部分" class="chapter " data-progress="2.1" style="left: 71.42857142857143%;"></a>
<a href="../chapter2/basic_operators.html" title="基本操作符" class="chapter " data-progress="2.2" style="left: 85.71428571428571%;"></a>
<a href="../chapter2/strings_and_characters.html" title="字符串和字符" class="chapter " data-progress="2.3" style="left: 100%;"></a>
</div>
</div>
<div class="page-inner">
<section class="normal" id="section-gitbook_15">
<section class="normal" id="section-gitbook_8">
<h1 id="-swift">关于 Swift</h1>
<p>Swift 是一种新的编程语言,用于编写 iOS 和 OS X 应用程序。Swift 结合了 C 和 Objective-C 的优点并且不受C的兼容性的限制。Swift 使用安全的编程模式并添加了很多新特性这将使编程更简单扩展性更强也更有趣。除此之外Swift 还支持人见人爱的 Cocoa 和 Cocoa Touch 框架。拥有了这些特性Swift将重新定义软件开发。</p>

View File

@ -15,6 +15,8 @@
<meta name="generator" content="www.gitbook.io">
<link rel="next" href="../chapter2/basic_operators.html" />
<link rel="prev" href="../chapter2/the_basics.html" />
@ -44,7 +46,7 @@
<div class="book" data-level="2.1" data-basepath=".." data-revision="1401895096940">
<div class="book" data-level="2.1" data-basepath=".." data-revision="1401919801865">
<div class="book-header">
<!-- Actions Left -->
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
@ -171,6 +173,24 @@
</a>
</li>
<li class="chapter " data-level="2.2" data-path="chapter2/basic_operators.html">
<a href="../chapter2/basic_operators.html">
<i class="fa fa-check"></i> <b>2.2.</b> 基本操作符
</a>
</li>
<li class="chapter " data-level="2.3" data-path="chapter2/strings_and_characters.html">
<a href="../chapter2/strings_and_characters.html">
<i class="fa fa-check"></i> <b>2.3.</b> 字符串和字符
</a>
</li>
@ -195,28 +215,32 @@
<div class="page-wrapper" tabindex="-1">
<div class="book-progress">
<div class="bar">
<div class="inner" style="width: 100%;min-width: 80%;"></div>
<div class="inner" style="width: 71.42857142857143%;min-width: 57.142857142857146%;"></div>
</div>
<div class="chapters">
<a href="../index.html" title="Introduction" class="chapter done new-chapter" data-progress="0" style="left: 0%;"></a>
<a href="../chapter1/README.html" title="欢迎使用 Swift" class="chapter done new-chapter" data-progress="1" style="left: 20%;"></a>
<a href="../chapter1/README.html" title="欢迎使用 Swift" class="chapter done new-chapter" data-progress="1" style="left: 14.285714285714286%;"></a>
<a href="../chapter1/swift.html" title="关于 Swift" class="chapter done " data-progress="1.1" style="left: 40%;"></a>
<a href="../chapter1/swift.html" title="关于 Swift" class="chapter done " data-progress="1.1" style="left: 28.571428571428573%;"></a>
<a href="../chapter1/a_swift_tour.html" title="Swift 初见" class="chapter done " data-progress="1.2" style="left: 60%;"></a>
<a href="../chapter1/a_swift_tour.html" title="Swift 初见" class="chapter done " data-progress="1.2" style="left: 42.857142857142854%;"></a>
<a href="../chapter2/the_basics.html" title="Swift 教程" class="chapter done new-chapter" data-progress="2" style="left: 80%;"></a>
<a href="../chapter2/the_basics.html" title="Swift 教程" class="chapter done new-chapter" data-progress="2" style="left: 57.142857142857146%;"></a>
<a href="../chapter2/article_1.html" title="基础部分" class="chapter done " data-progress="2.1" style="left: 100%;"></a>
<a href="../chapter2/article_1.html" title="基础部分" class="chapter done " data-progress="2.1" style="left: 71.42857142857143%;"></a>
<a href="../chapter2/basic_operators.html" title="基本操作符" class="chapter " data-progress="2.2" style="left: 85.71428571428571%;"></a>
<a href="../chapter2/strings_and_characters.html" title="字符串和字符" class="chapter " data-progress="2.3" style="left: 100%;"></a>
</div>
</div>
<div class="page-inner">
<section class="normal" id="section-gitbook_16">
<section class="normal" id="section-gitbook_9">
<h1 id="-">基础部分</h1>
<p>Swift 是 iOS 和 OS X 应用开发的一门新语言。然而,如果你有 C 或者 Objective-C 开发经验的话,你会发现 Swift 的很多内容都是你熟悉的。</p>
@ -255,10 +279,34 @@ var currentLoginAttempt = 0
<p>你可以用任何你喜欢的字符作为常量和变量名包括Unicode字符</p>
<pre><code> let π = 3.14159
let 你好 = &quot;你好世界&quot;
let 🐶🐮 = &quot;dogcow&quot;
</code></pre><p>常量与变量名不能包含数学符号,箭头,保留的(或者非法的)Unicode码位连线与制表符。尽管常量与变量名中可以包含数字但是它们不能以数字打头。</p>
<p>一旦你将常量或者变量声明为确定的类型,你就不能使用相同的名字再次进行声明,或者以改变其存储的值为其他类型。同时,你也不能将常量与变量进行互转。</p>
<blockquote>
<p>注意如果你需要使用与Swift保留关键字相同的名称作为常量或者变量名你可以使用反引号(`)将关键字围住的方式将其作为名字使用。无论如何,你应当避免使用关键字作为常量或变量名,除非你别无选择。</p>
</blockquote>
<p>你可以更改现有的变量值为其他同类型的值,在下面的例子中,<code>friendlyWelcome</code>的值从<code>&quot;Hello!&quot;</code>改为了<code>&quot;Bonjour!&quot;</code>:</p>
<pre><code> var friendlyWelcome = &quot;Hello!&quot;
friendlyWelcome = &quot;Bonjour!&quot;
// friendlyWelcome is now &quot;Bonjour!&quot;
</code></pre><p>和变量不一样,常量的值一旦被确定以后就不能更改了。尝试这样做会在编译时报错:</p>
<pre><code> let languageName = &quot;Swift&quot;
languageName = &quot;Swift++&quot;
// this is a compile-time error - languageName cannot be changed
</code></pre><h3 id="-">输出常量和变量</h3>
<p>你可以用<code>println</code>函数来输出当前常量或变量的值:</p>
<pre><code> println(friendlyWelcome)
// prints &quot;Bonjour!&quot;
</code></pre><p><code>println</code>是一个用来输出的全局函数输出的内容会在最后带换行。如果你用Xcode<code>println</code>将会输出内容到“console”面板上。(另一种函数叫<code>print</code>,唯一区别是在输出内容最后不会加入换行。)</p>
<p><code>println</code>函数输出传入的<code>String</code>值:</p>
<pre><code> println(&quot;This is a string&quot;)
// prints &quot;This is a string&quot;
</code></pre><p>像Cocoa里的<code>NSLog</code>函数一样,<code>println</code>函数可以输出更复杂的信息。这些信息可以包含当前常量和变量的值。</p>
<p>Swift用字符串插值string interpolation的方式把常量名或者变量名当做占位符加入到长字符串中Swift会用当前常量或变量的值替换这些占位符。将常量或变量名放入反斜杠符加一对圆括号中<code>&quot;\()&quot;</code></p>
<pre><code> println(&quot;The current value of friendlyWelcome is \(friendlyWelcome)&quot;)
// prints &quot;The current value of friendlyWelcome is Bonjour!
</code></pre><blockquote>
<p>注意:字符串插值所有可用的选项在 字符串插值 这章中讲述。</p>
</blockquote>
@ -269,9 +317,11 @@ var currentLoginAttempt = 0
</div>
<a href="../chapter2/the_basics.html" class="navigation navigation-prev navigation-unique" aria-label="Previous page: Swift 教程"><i class="fa fa-angle-left"></i></a>
<a href="../chapter2/the_basics.html" class="navigation navigation-prev " aria-label="Previous page: Swift 教程"><i class="fa fa-angle-left"></i></a>
<a href="../chapter2/basic_operators.html" class="navigation navigation-next " aria-label="Next page: 基本操作符"><i class="fa fa-angle-right"></i></a>
</div>
</div>

View File

@ -0,0 +1,293 @@
<!DOCTYPE HTML>
<html lang="en-US" manifest="../manifest.appcache">
<head prefix="og: http://ogp.me/ns# book: http://ogp.me/ns/book#">
<meta charset="UTF-8">
<title>基本操作符 | Swift 编程语言</title>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<meta name="robots" content="index, follow">
<meta name="author" content="">
<meta name="description" content="Swift 是苹果在 WWDC 2014 上发布的一款全新的编程语言,本书译自苹果官方的 Swift 教程《The Swift Programming Language》。">
<meta name="keywords" content="gitbook,github" >
<meta name="generator" content="www.gitbook.io">
<link rel="next" href="../chapter2/strings_and_characters.html" />
<link rel="prev" href="../chapter2/article_1.html" />
<meta property="og:title" content="基本操作符 | Swift 编程语言">
<meta property="og:site_name" content="Swift 编程语言">
<meta property="og:type" content="book">
<meta property="og:locale" content="en_US">
<meta property="book:author" content="https://github.com/">
<meta property="book:tag" content="GitBook">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<link rel="shortcut icon" href="../gitbook/images/favicon.ico" type="image/x-icon">
</head>
<body>
<link rel="stylesheet" href="../gitbook/style.css">
<div class="book" data-level="2.2" data-basepath=".." data-revision="1401919801865">
<div class="book-header">
<!-- Actions Left -->
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
<a href="https://github.com/null" target="_blank" class="btn pull-left home-bookmark" aria-label="GitHub home"><i class="fa fa-bookmark-o"></i></a>
<a href="#" class="btn pull-left toggle-search" aria-label="Toggle search"><i class="fa fa-search"></i></a>
<span id="font-settings-wrapper">
<a href="#" class="btn pull-left toggle-font-settings" aria-label="Toggle font settings"><i class="fa fa-font"></i>
</a>
<div class="dropdown-menu font-settings">
<div class="dropdown-caret">
<span class="caret-outer"></span>
<span class="caret-inner"></span>
</div>
<div class="btn-group btn-block">
<button id="reduce-font-size" class="btn btn-default">A</button>
<button id="enlarge-font-size" class="btn btn-default">A</button>
</div>
<ul class="list-group font-family-list">
<li class="list-group-item" data-font="0">Serif</li>
<li class="list-group-item" data-font="1">Sans</li>
</ul>
<div class="btn-group btn-group-xs btn-block color-theme-list">
<button type="button" class="btn btn-default" id="color-theme-preview-0" data-theme="0">White</button>
<button type="button" class="btn btn-default" id="color-theme-preview-1" data-theme="1">Sepia</button>
<button type="button" class="btn btn-default" id="color-theme-preview-2" data-theme="2">Night</button>
</div>
</div>
</span>
<!-- Actions Right -->
<a href="#" target="_blank" class="btn pull-right google-plus-sharing-link sharing-link" data-sharing="google-plus" aria-label="Share on Google Plus"><i class="fa fa-google-plus"></i></a>
<a href="#" target="_blank" class="btn pull-right facebook-sharing-link sharing-link" data-sharing="facebook" aria-label="Share on Facebook"><i class="fa fa-facebook"></i></a>
<a href="#" target="_blank" class="btn pull-right twitter-sharing-link sharing-link" data-sharing="twitter" aria-label="Share on Twitter"><i class="fa fa-twitter"></i></a>
<!-- Title -->
<h1>
<i class="fa fa-spinner fa-spin"></i>
<a href="../" >Swift 编程语言</a>
</h1>
</div>
<div class="book-summary">
<div class="book-search">
<input type="text" placeholder="Search" class="form-control" />
</div>
<ul class="summary">
<li data-level="0" data-path="index.html">
<a href="../"><i class="fa fa-check"></i> Introduction</a>
</li>
<li class="chapter " data-level="1" data-path="chapter1/README.html">
<a href="../chapter1/README.html">
<i class="fa fa-check"></i> <b>1.</b> 欢迎使用 Swift
</a>
<ul class="articles">
<li class="chapter " data-level="1.1" data-path="chapter1/swift.html">
<a href="../chapter1/swift.html">
<i class="fa fa-check"></i> <b>1.1.</b> 关于 Swift
</a>
</li>
<li class="chapter " data-level="1.2" data-path="chapter1/a_swift_tour.html">
<a href="../chapter1/a_swift_tour.html">
<i class="fa fa-check"></i> <b>1.2.</b> Swift 初见
</a>
</li>
</ul>
</li>
<li class="chapter " data-level="2" data-path="chapter2/the_basics.html">
<a href="../chapter2/the_basics.html">
<i class="fa fa-check"></i> <b>2.</b> Swift 教程
</a>
<ul class="articles">
<li class="chapter " data-level="2.1" data-path="chapter2/article_1.html">
<a href="../chapter2/article_1.html">
<i class="fa fa-check"></i> <b>2.1.</b> 基础部分
</a>
</li>
<li class="chapter " data-level="2.2" data-path="chapter2/basic_operators.html">
<a href="../chapter2/basic_operators.html">
<i class="fa fa-check"></i> <b>2.2.</b> 基本操作符
</a>
</li>
<li class="chapter " data-level="2.3" data-path="chapter2/strings_and_characters.html">
<a href="../chapter2/strings_and_characters.html">
<i class="fa fa-check"></i> <b>2.3.</b> 字符串和字符
</a>
</li>
</ul>
</li>
<li class="divider"></li>
<li>
<a href="http://www.gitbook.io/" target="blank" class="gitbook-link">Generated using GitBook</a>
</li>
<li style="margin-left:15%;"> <iframe src="http://ghbtns.com/github-btn.html?user=numbbbbb&repo=the-swift-programming-language-in-chinese&type=watch&count=true&size=large"
allowtransparency="true" frameborder="0" scrolling="0" width="170" height="30"></iframe></li>
</ul>
</div>
<div class="book-body">
<div class="body-inner">
<div class="page-wrapper" tabindex="-1">
<div class="book-progress">
<div class="bar">
<div class="inner" style="width: 85.71428571428571%;min-width: 71.42857142857143%;"></div>
</div>
<div class="chapters">
<a href="../index.html" title="Introduction" class="chapter done new-chapter" data-progress="0" style="left: 0%;"></a>
<a href="../chapter1/README.html" title="欢迎使用 Swift" class="chapter done new-chapter" data-progress="1" style="left: 14.285714285714286%;"></a>
<a href="../chapter1/swift.html" title="关于 Swift" class="chapter done " data-progress="1.1" style="left: 28.571428571428573%;"></a>
<a href="../chapter1/a_swift_tour.html" title="Swift 初见" class="chapter done " data-progress="1.2" style="left: 42.857142857142854%;"></a>
<a href="../chapter2/the_basics.html" title="Swift 教程" class="chapter done new-chapter" data-progress="2" style="left: 57.142857142857146%;"></a>
<a href="../chapter2/article_1.html" title="基础部分" class="chapter done " data-progress="2.1" style="left: 71.42857142857143%;"></a>
<a href="../chapter2/basic_operators.html" title="基本操作符" class="chapter done " data-progress="2.2" style="left: 85.71428571428571%;"></a>
<a href="../chapter2/strings_and_characters.html" title="字符串和字符" class="chapter " data-progress="2.3" style="left: 100%;"></a>
</div>
</div>
<div class="page-inner">
<section class="normal" id="section-gitbook_10">
<h1 id="-">基本操作符</h1>
</section>
</div>
</div>
</div>
<a href="../chapter2/article_1.html" class="navigation navigation-prev " aria-label="Previous page: 基础部分"><i class="fa fa-angle-left"></i></a>
<a href="../chapter2/strings_and_characters.html" class="navigation navigation-next " aria-label="Next page: 字符串和字符"><i class="fa fa-angle-right"></i></a>
</div>
</div>
<script src="http://cdn.bootcss.com/ace/1.1.3/ace.js"></script>
<script src="http://cdn.bootcss.com/ace/1.1.3/mode-javascript.js"></script>
<script src="../gitbook/jsrepl/jsrepl.js" id="jsrepl-script"></script>
<script src="../gitbook/app.js"></script>
<script src="../gitbook/plugins/gitbook-plugin-mixpanel/plugin.js"></script>
<script src="http://cdn.mathjax.org/mathjax/2.0-latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script src="../gitbook/plugins/gitbook-plugin-mathjax/plugin.js"></script>
<script>
require(["gitbook"], function(gitbook) {
var config = {};
gitbook.start(config);
});
</script>
</body>
</html>

View File

@ -0,0 +1,501 @@
<!DOCTYPE HTML>
<html lang="en-US" manifest="../manifest.appcache">
<head prefix="og: http://ogp.me/ns# book: http://ogp.me/ns/book#">
<meta charset="UTF-8">
<title>字符串和字符 | Swift 编程语言</title>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<meta name="robots" content="index, follow">
<meta name="author" content="">
<meta name="description" content="Swift 是苹果在 WWDC 2014 上发布的一款全新的编程语言,本书译自苹果官方的 Swift 教程《The Swift Programming Language》。">
<meta name="keywords" content="gitbook,github" >
<meta name="generator" content="www.gitbook.io">
<link rel="prev" href="../chapter2/basic_operators.html" />
<meta property="og:title" content="字符串和字符 | Swift 编程语言">
<meta property="og:site_name" content="Swift 编程语言">
<meta property="og:type" content="book">
<meta property="og:locale" content="en_US">
<meta property="book:author" content="https://github.com/">
<meta property="book:tag" content="GitBook">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<link rel="shortcut icon" href="../gitbook/images/favicon.ico" type="image/x-icon">
</head>
<body>
<link rel="stylesheet" href="../gitbook/style.css">
<div class="book" data-level="2.3" data-basepath=".." data-revision="1401919801865">
<div class="book-header">
<!-- Actions Left -->
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
<a href="https://github.com/null" target="_blank" class="btn pull-left home-bookmark" aria-label="GitHub home"><i class="fa fa-bookmark-o"></i></a>
<a href="#" class="btn pull-left toggle-search" aria-label="Toggle search"><i class="fa fa-search"></i></a>
<span id="font-settings-wrapper">
<a href="#" class="btn pull-left toggle-font-settings" aria-label="Toggle font settings"><i class="fa fa-font"></i>
</a>
<div class="dropdown-menu font-settings">
<div class="dropdown-caret">
<span class="caret-outer"></span>
<span class="caret-inner"></span>
</div>
<div class="btn-group btn-block">
<button id="reduce-font-size" class="btn btn-default">A</button>
<button id="enlarge-font-size" class="btn btn-default">A</button>
</div>
<ul class="list-group font-family-list">
<li class="list-group-item" data-font="0">Serif</li>
<li class="list-group-item" data-font="1">Sans</li>
</ul>
<div class="btn-group btn-group-xs btn-block color-theme-list">
<button type="button" class="btn btn-default" id="color-theme-preview-0" data-theme="0">White</button>
<button type="button" class="btn btn-default" id="color-theme-preview-1" data-theme="1">Sepia</button>
<button type="button" class="btn btn-default" id="color-theme-preview-2" data-theme="2">Night</button>
</div>
</div>
</span>
<!-- Actions Right -->
<a href="#" target="_blank" class="btn pull-right google-plus-sharing-link sharing-link" data-sharing="google-plus" aria-label="Share on Google Plus"><i class="fa fa-google-plus"></i></a>
<a href="#" target="_blank" class="btn pull-right facebook-sharing-link sharing-link" data-sharing="facebook" aria-label="Share on Facebook"><i class="fa fa-facebook"></i></a>
<a href="#" target="_blank" class="btn pull-right twitter-sharing-link sharing-link" data-sharing="twitter" aria-label="Share on Twitter"><i class="fa fa-twitter"></i></a>
<!-- Title -->
<h1>
<i class="fa fa-spinner fa-spin"></i>
<a href="../" >Swift 编程语言</a>
</h1>
</div>
<div class="book-summary">
<div class="book-search">
<input type="text" placeholder="Search" class="form-control" />
</div>
<ul class="summary">
<li data-level="0" data-path="index.html">
<a href="../"><i class="fa fa-check"></i> Introduction</a>
</li>
<li class="chapter " data-level="1" data-path="chapter1/README.html">
<a href="../chapter1/README.html">
<i class="fa fa-check"></i> <b>1.</b> 欢迎使用 Swift
</a>
<ul class="articles">
<li class="chapter " data-level="1.1" data-path="chapter1/swift.html">
<a href="../chapter1/swift.html">
<i class="fa fa-check"></i> <b>1.1.</b> 关于 Swift
</a>
</li>
<li class="chapter " data-level="1.2" data-path="chapter1/a_swift_tour.html">
<a href="../chapter1/a_swift_tour.html">
<i class="fa fa-check"></i> <b>1.2.</b> Swift 初见
</a>
</li>
</ul>
</li>
<li class="chapter " data-level="2" data-path="chapter2/the_basics.html">
<a href="../chapter2/the_basics.html">
<i class="fa fa-check"></i> <b>2.</b> Swift 教程
</a>
<ul class="articles">
<li class="chapter " data-level="2.1" data-path="chapter2/article_1.html">
<a href="../chapter2/article_1.html">
<i class="fa fa-check"></i> <b>2.1.</b> 基础部分
</a>
</li>
<li class="chapter " data-level="2.2" data-path="chapter2/basic_operators.html">
<a href="../chapter2/basic_operators.html">
<i class="fa fa-check"></i> <b>2.2.</b> 基本操作符
</a>
</li>
<li class="chapter " data-level="2.3" data-path="chapter2/strings_and_characters.html">
<a href="../chapter2/strings_and_characters.html">
<i class="fa fa-check"></i> <b>2.3.</b> 字符串和字符
</a>
</li>
</ul>
</li>
<li class="divider"></li>
<li>
<a href="http://www.gitbook.io/" target="blank" class="gitbook-link">Generated using GitBook</a>
</li>
<li style="margin-left:15%;"> <iframe src="http://ghbtns.com/github-btn.html?user=numbbbbb&repo=the-swift-programming-language-in-chinese&type=watch&count=true&size=large"
allowtransparency="true" frameborder="0" scrolling="0" width="170" height="30"></iframe></li>
</ul>
</div>
<div class="book-body">
<div class="body-inner">
<div class="page-wrapper" tabindex="-1">
<div class="book-progress">
<div class="bar">
<div class="inner" style="width: 100%;min-width: 85.71428571428571%;"></div>
</div>
<div class="chapters">
<a href="../index.html" title="Introduction" class="chapter done new-chapter" data-progress="0" style="left: 0%;"></a>
<a href="../chapter1/README.html" title="欢迎使用 Swift" class="chapter done new-chapter" data-progress="1" style="left: 14.285714285714286%;"></a>
<a href="../chapter1/swift.html" title="关于 Swift" class="chapter done " data-progress="1.1" style="left: 28.571428571428573%;"></a>
<a href="../chapter1/a_swift_tour.html" title="Swift 初见" class="chapter done " data-progress="1.2" style="left: 42.857142857142854%;"></a>
<a href="../chapter2/the_basics.html" title="Swift 教程" class="chapter done new-chapter" data-progress="2" style="left: 57.142857142857146%;"></a>
<a href="../chapter2/article_1.html" title="基础部分" class="chapter done " data-progress="2.1" style="left: 71.42857142857143%;"></a>
<a href="../chapter2/basic_operators.html" title="基本操作符" class="chapter done " data-progress="2.2" style="left: 85.71428571428571%;"></a>
<a href="../chapter2/strings_and_characters.html" title="字符串和字符" class="chapter done " data-progress="2.3" style="left: 100%;"></a>
</div>
</div>
<div class="page-inner">
<section class="normal" id="section-gitbook_11">
<h1 id="-strings-and-characters-">字符串和字符 (Strings and Characters)</h1>
<p><strong>String</strong> 是一个有序的字符集合,例如 &quot;hello, world&quot;, &quot;albatross&quot;。Swift 字符串通过 <strong>String</strong> 类型来表示,也可以表示为 <strong>Character</strong> 类型值的集合。</p>
<p>Swift 的 <strong>String</strong><strong>Character</strong> 类型提供了一个快速的,兼容 Unicode 的方式来处理代码中的文本信息。创建和操作字符串的语法与 C的操作方式相似轻量并且易读。字符串连接操作只需要简单地通过 <code>+</code> 号将两个字符串相连即可。与 Swift 中其他值一样,能否更改字符串的值,取决于其被定义为常量还是变量。</p>
<p>尽管语法简易,但 <strong>String</strong> 类型是一种快速、现代化的字符串实现。每一个字符串都是由独立编码的 Unicode 字符组成并提供了用于访问这些字符在不同的Unicode表示的支持。</p>
<p><strong>String</strong> 也可以用于在常量、变量、字面量和表达式中进行字符串插值,这使得创建用于展示、存储和打印的字符串变得轻松自如。</p>
<blockquote>
<p>注意:</p>
<p>Swift 的 <strong>String</strong> 类型与 Foundation NSString 类进行了无缝桥接。如果您利用 Cocoa 或 Cocoa Touch 中的 Foundation 框架进行工作,整个 NSString API 都可以调用您创建的任意 String 类型的值,您额外还可以在任意 API 中使用本章介绍的 <strong>String</strong> 特性。您也可以在任意要求传入NSString 实例作为参数的 API 中使用 <strong>String</strong> 类型的值进行替换。</p>
<p>更多关于在 Foundation 和 Cocoa 中使用 <strong>String</strong> 的信息请查看 <a href="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/index.html#//apple_ref/doc/uid/TP40014216" target="_blank">Using Swift with Cocoa and Objective-C</a></p>
</blockquote>
<h3 id="-">字符串字面量</h3>
<p>您可以在您的代码中包含一段预定义的字符串值作为字符串字面量。字符串字面量是由双引号包裹着的具有固定顺序的文本字符集。</p>
<p>字符串字面量可以用于为常量和变量提供初始值。</p>
<pre><code>let someString = &quot;Some string literal value&quot;
</code></pre><blockquote>
<p>注意:</p>
<p><code>someString</code> 变量通过字符串字面量进行初始化Swift 因此推断其为 <strong>String</strong> 类型。</p>
</blockquote>
<p>字符串字面量可以包含以下特殊字符:</p>
<ul>
<li>转移特殊字符 <code>\0</code> (空字符)、<code>\\</code>(反斜线)、<code>\t</code> (水平制表符)、<code>\n</code> (换行符)、<code>\r</code> (回车符)、<code>\&quot;</code> (双引号)、<code>\&#39;</code> (单引号)。</li>
<li>单字节 Unicode 标量,写成 <code>\xnn</code>,其中 nn 为两位十六进制数。</li>
<li>双字节 Unicode 标量,写成 <code>\unnnn</code>,其中 nnnn 为四位十六进制数。</li>
<li>四字节 Unicode 标量,写成 <code>\Unnnnnnnn</code>,其中 nnnnnnnn 为八位十六进制数。</li>
</ul>
<p>下面的代码为各种特殊字符的使用示例。</p>
<p><code>wiseWords</code> 常量包含了两个转移特殊字符 (双括号)<code>dollarSign</code><code>blackHeart</code><code>sparklingHeart</code> 常量演示了三种不同格式的 Unicode 标量:</p>
<pre><code>let wiseWords = &quot;\&quot;Imagination is more important than knowledge\&quot; - Einstein&quot;
// &quot;Imagination is more important than knowledge&quot; - Einstein
let dollarSign = &quot;\x24&quot; // $, Unicode scalar U+0024
let blackHeart = &quot;\u2665&quot; // ♥, Unicode scalar U+2665
let sparklingHeart = &quot;\U0001F496&quot; // 💖, Unicode scalar U+1F496
</code></pre><h3 id="-">初始化空字符串</h3>
<p>为了构造一个很长的字符串,可以创建一个空字符串作为初始值。可以将空的字符串字面量赋值给变量,也可以初始化一个新的 <strong>String</strong> 实例:</p>
<pre><code>var emptyString = &quot;&quot; // empty string literal
var anotherEmptyString = String() // initializer syntax
// 这两个字符串都为空,并且两者等价
</code></pre><p>您可以通过检查其 <strong>Boolean</strong> 类型的 <code>isEmpty</code> 属性来判断该字符串是否为空:</p>
<pre><code>if emptyString.isEmpty {
println(&quot;Nothing to see here&quot;)
}
// 打印 &quot;Nothing to see here&quot;
</code></pre><h3 id="-">字符串可变性</h3>
<p>您可以通过将一个特定字符串分配给一个变量来对其进行修改,或者分配给一个常量来保证其不会被修改:</p>
<pre><code>var variableString = &quot;Horse&quot;
variableString += &quot; and carriage&quot;
// variableString 现在为 &quot;Horse and carriage&quot;
let constantString = &quot;Highlander&quot;
constantString += &quot; and another Highlander&quot;
// 这会报告一个编译错误(compile-time error) - 常量不可以被修改。
</code></pre><blockquote>
<p>注意:</p>
<p>在 Objective-C 和 Cocoa 中,您通过选择两个不同的类( NSString 和 NSMutableString )来指定该字符串是否可以被修改Swift中的字符串是否可以修改仅通过定义的是变量还是常量来决定实现了多种类型可变性操作的统一。</p>
</blockquote>
<h3 id="-">字符串是值类型</h3>
<p>Swift 的 <strong>String</strong> 类型是值类型。如果您创建了一个新的字符串,那么当其进行常量、变量赋值操作或在函数/方法中传递时,会进行值拷贝。任何情况下,都会对已有字符串值创建新副本,并对该新副本进行传递或赋值。值类型在 <a href="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ClassesAndStructures.html#//apple_ref/doc/uid/TP40014097-CH13-XID_104" target="_blank">Structures and Enumerations Are Value Types</a> 中进行了说明。</p>
<blockquote>
<p>注意:</p>
<p>其 Cocoa 中的 NSString 不同,当您在 Cocoa 中创建了一个 NSString 实例,并将其传递给一个函数/方法,或者赋值给一个变量,您永远都是传递或赋值同一个 NSString 实例的一个引用。除非您特别要求其进行值拷贝,否则字符串不会进行赋值新副本操作。</p>
</blockquote>
<p>Swift 默认字符串拷贝的方式保证了在函数/方法中传递的是字符串的值,其明确了无论该值来自于哪里,都是您独自拥有的。您可以放心您传递的字符串本身不会被更改。</p>
<p>在实际编译时Swift编译器会优化字符串的使用使实际的复制只发生在绝对必要的情况下这意味着您始终可以将字符串作为值类型的同时获得极高的性能。</p>
<h4 id="-characters-">使用字符(Characters)</h4>
<p>Swift 的 <strong>String</strong> 类型表示特定序列的字符值的集合。每一个字符值代表一个 Unicode 字符。您可利用 for-in 循环来遍历字符串中的每一个字符:</p>
<pre><code>for character in &quot;Dog!🐶&quot; {
println(character)
}
// D
// o
// g
// !
// 🐶
</code></pre><p>for-in 循环在<a href="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ControlFlow.html#//apple_ref/doc/uid/TP40014097-CH9-XID_154" target="_blank">For Loops</a>中进行了详细描述。</p>
<p>另外,通过标明一个 <strong>Character</strong> 类型注解并通过字符字面量进行赋值,可以建立一个独立的字符常量或变量:</p>
<pre><code>let yenSign: Character = &quot;¥&quot;
</code></pre><h3 id="-">计算字符数量</h3>
<p>通过调用全局 <code>countElements</code> 函数并将字符串作为参数进行传递可以获取该字符串的字符数量。</p>
<pre><code>let unusualMenagerie = &quot;Koala 🐨, Snail 🐌, Penguin 🐧, Dromedary 🐪&quot;
println(&quot;unusualMenagerie has \(countElements(unusualMenagerie)) characters&quot;)
// prints &quot;unusualMenagerie has 40 characters&quot;
</code></pre><blockquote>
<p>注意:</p>
<p>不同的 Unicode 字符以及相同 Unicode 字符的不同表示方式可能需要不同数量的内存空间来存储所以Swift 中的字符在一个字符串中并不一定占用相同的内存空间。因此,字符串的长度不得不通过迭代字符串中每一个字符的长度来进行计算。如果您正在处理一个长字符串,需要注意 <code>countElements</code> 函数必须遍历字符串中的字符以精准计算字符串的长度。</p>
<p>另外需要注意的是通过 <code>countElements</code> 返回的字符数量并不总是与包含相同字符的 NSString 的 <code>length</code> 属性相同。NSString 的 <code>length</code> 属性是基于利用 UTF-16 表示的十六位代码单元数字,而不是基于 Unicode 字符。为了解决这个问题NSString 的 <code>length</code> 属性在被 Swift的 <strong>String</strong> 访问时会成为 <code>utf16count</code></p>
</blockquote>
<h3 id="-">连接字符串和字符</h3>
<p>字符串和字符的值可以通过加法运算符 (+) 相加在一起并创建一个新的字符串值:</p>
<pre><code>let string1 = &quot;hello&quot;
let string2 = &quot; there&quot;
let character1: Character = &quot;!&quot;
let character2: Character = &quot;?&quot;
let stringPlusCharacter = string1 + character1 // 等于 &quot;hello!&quot;
let stringPlusString = string1 + string2 // 等于 &quot;hello there&quot;
let characterPlusString = character1 + string1 // 等于 &quot;!hello&quot;
let characterPlusCharacter = character1 + character2 // 等于 &quot;!?&quot;
</code></pre><p>您也可以通过加法赋值运算符 (+=) 将一个字符串或者字符添加到一个已经存在字符串变量上:</p>
<pre><code>var instruction = &quot;look over&quot;
instruction += string2
// instruction 现在等于 &quot;look over there&quot;
var welcome = &quot;good morning&quot;
welcome += character1
// welcome 现在等于 &quot;good morning!&quot;
</code></pre><blockquote>
<p>注意:</p>
<p>您不能将一个字符串或者字符添加到一个已经存在的字符变量上,因为字符变量只能包含一个字符。</p>
</blockquote>
<h3 id="-">字符串插值</h3>
<p>字符串插值是一种全新的构建字符串的方式,可以在其中包含常量、变量、字面量和表达式。您插入的字符串字面量的每一项都被包裹在以反斜线为前缀的圆括号中:</p>
<pre><code>let multiplier = 3
let message = &quot;\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)&quot;
// message is &quot;3 times 2.5 is 7.5&quot;
</code></pre><p>在上面的例子中,<code>multiplier</code> 作为 <code>\(multiplier)</code> 被插入到一个字符串字面量中。当创建字符串执行插值计算时此占位符会被替换为 <code>multiplier</code> 实际的值。</p>
<p><code>multiplier</code> 的值也作为字符串中后面表达式的一部分。该表达式计算 <code>Double(multiplier) * 2.5</code> 的值并将结果 (7.5) 插入到字符串中。在这个例子中,表达式写为 <code>\(Double(multiplier) * 2.5)</code> 并包含在字符串字面量中。</p>
<blockquote>
<p>注意:</p>
<p>您插值字符串中写在括号中的表达式不能包含非转义双引号 (&quot;) 和反斜杠 (\),并且不能包含回车或换行符。</p>
</blockquote>
<h3 id="-">比较字符串</h3>
<p>Swift 提供了三种方式来比较字符串的值:字符串相等,前缀相等和后缀相等。</p>
<h5 id="-">字符串相等</h5>
<p>如果两个字符串以同一顺序包含完全相同的字符,则认为两者字符串相等:</p>
<pre><code>let quotation = &quot;We&#39;re a lot alike, you and I.&quot;
let sameQuotation = &quot;We&#39;re a lot alike, you and I.&quot;
if quotation == sameQuotation {
println(&quot;These two strings are considered equal&quot;)
}
// prints &quot;These two strings are considered equal&quot;
</code></pre><h5 id="-">前缀/后缀相等</h5>
<p>通过调用字符串的 <code>hasPrefix</code>/<code>hasSuffix</code> 方法来检查字符串是否拥有特定前缀/后缀。两个方法均需要以字符串作为参数传入并传出 <strong>Boolean</strong> 值。两个方法均执行基本字符串和前缀/后缀字符串之间逐个字符的比较操作。</p>
<p>下面的例子以一个字符串数组表示莎士比亚话剧 <code>罗密欧与朱丽叶</code> 中前两场的场景位置:</p>
<pre><code>let romeoAndJuliet = [
&quot;Act 1 Scene 1: Verona, A public place&quot;,
&quot;Act 1 Scene 2: Capulet&#39;s mansion&quot;,
&quot;Act 1 Scene 3: A room in Capulet&#39;s mansion&quot;,
&quot;Act 1 Scene 4: A street outside Capulet&#39;s mansion&quot;,
&quot;Act 1 Scene 5: The Great Hall in Capulet&#39;s mansion&quot;,
&quot;Act 2 Scene 1: Outside Capulet&#39;s mansion&quot;,
&quot;Act 2 Scene 2: Capulet&#39;s orchard&quot;,
&quot;Act 2 Scene 3: Outside Friar Lawrence&#39;s cell&quot;,
&quot;Act 2 Scene 4: A street in Verona&quot;,
&quot;Act 2 Scene 5: Capulet&#39;s mansion&quot;,
&quot;Act 2 Scene 6: Friar Lawrence&#39;s cell&quot;
]
</code></pre><p>您可以利用 <code>hasPrefix</code> 方法来计算话剧中第一幕的场景数:</p>
<pre><code>var act1SceneCount = 0
for scene in romeoAndJuliet {
if scene.hasPrefix(&quot;Act 1 &quot;) {
++act1SceneCount
}
}
println(&quot;There are \(act1SceneCount) scenes in Act 1&quot;)
// prints &quot;There are 5 scenes in Act 1&quot;
</code></pre><h5 id="-">大写和小写字符串</h5>
<p>您可以通过字符串的 <code>uppercaseString</code><code>lowercaseString</code> 属性来访问一个字符串的大写/小写版本。</p>
<pre><code>let normal = &quot;Could you help me, please?&quot;
let shouty = normal.uppercaseString
// shouty 值为 &quot;COULD YOU HELP ME, PLEASE?&quot;
let whispered = normal.lowercaseString
// whispered 值为 &quot;could you help me, please?&quot;
</code></pre><h3 id="unicode">Unicode</h3>
<p>Unicode 是文本编码和表示的国际标准。它使您可以用标准格式表示来自任意语言几乎所有的字符,并能够对文本文件或网页这样的外部资源中的字符进行读写操作。</p>
<p>Swift 的字符串和字符类型是完全兼容 Unicode 的,它支持如下所述的一系列不同的 Unicode 编码。</p>
<h6 id="unicode-terminology-">Unicode 术语(Terminology)</h6>
<p>Unicode 中每一个字符都可以被解释为一个或多个 unicode 标量。字符的 unicode 标量是一个唯一的21位数字(和名称),例如 <code>U+0061</code> 表示小写的拉丁字母A (&quot;a&quot;)<code>U+1F425</code> 表示正面站立的鸡宝宝 (&quot;🐥&quot;)</p>
<p>当 Unicode 字符串被写进文本文件或其他存储结构当中,这些 unicode 标量将会按照 Unicode 定义的集中格式之一进行编码。其包括 <code>UTF-8</code> (以8位代码单元进行编码) 和 <code>UTF-16</code> (以16位代码单元进行编码)。</p>
<h5 id="-unicode-">字符串的 Unicode 表示</h5>
<p>Swift 提供了几种不同的方式来访问字符串的 Unicode 表示。</p>
<p>您可以利用 <code>for-in</code> 来对字符串进行遍历,从而以 Unicode 字符的方式访问每一个字符值。该过程在 <a href="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/StringsAndCharacters.html#//apple_ref/doc/uid/TP40014097-CH7-XID_376" target="_blank">Working with Characters</a> 中进行了描述。</p>
<p>另外,能够以其他三种 Unicode 兼容的方式访问字符串的值:</p>
<ul>
<li>UTF-8 代码单元集合 (利用字符串的 <code>utf8</code> 属性进行访问)</li>
<li>UTF-16 代码单元集合 (利用字符串的 <code>utf16</code> 属性进行访问)</li>
<li>21位的 Unicode 标量值集合 (利用字符串的 <code>unicodeScalars</code> 属性进行访问)</li>
</ul>
<p>下面由 <code>D</code> <code>o</code> <code>g</code> <code>!</code><code>🐶</code> (狗脸表情Unicode 标量为 <code>U+1F436</code>)组成的字符串中的每一个字符代表着一种不同的表示:</p>
<pre><code>let dogString = &quot;Dog!🐶&quot;
</code></pre><h5 id="utf-8">UTF-8</h5>
<p>您可以通过遍历字符串的 <code>utf8</code> 属性来访问它的 <code>UTF-8</code> 表示。其为 <strong>UTF8View</strong> 类型的属性,<strong>UTF8View</strong> 是无符号8位 (<code>UInt8</code>) 值的集合,每一个 <code>UIn8</code> 都是一个字符的 UTF-8 表示:</p>
<pre><code>for codeUnit in dogString.utf8 {
print(&quot;\(codeUnit) &quot;)
}
print(&quot;\n&quot;)
// 68 111 103 33 240 159 144 182
</code></pre><p>上面的例子中前四个10进制代码单元值 (68, 111, 103, 33) 代表了字符 <code>D</code> <code>o</code> <code>g</code><code>!</code> ,他们的 UTF-8 表示与 ASCII 表示相同。后四个代码单元值 (240, 159, 144, 182) 是 <code>狗脸表情</code> 的4位 UTF-8 表示。</p>
<h5 id="utf-16">UTF-16</h5>
<p>您可以通过遍历字符串的 <code>utf16</code> 属性来访问它的 <code>UTF-16</code> 表示。其为 <strong>UTF16View</strong> 类型的属性,<strong>UTF16View</strong> 是无符号16位 (<code>UInt16</code>) 值的集合,每一个 <code>UInt16</code> 都是一个字符的 UTF-16 表示:</p>
<pre><code>for codeUnit in dogString.utf16 {
print(&quot;\(codeUnit) &quot;)
}
print(&quot;\n&quot;)
// 68 111 103 33 55357 56374
</code></pre><p>同样,前四个代码单元值 (68, 111, 103, 33) 代表了字符 <code>D</code> <code>o</code> <code>g</code><code>!</code> ,他们的 UTF-16 代码单元和 UTF-8 完全相同。</p>
<p>第五和第六个代码单元值 (55357 and 56374) 是 <code>狗脸表情</code> 字符的UTF-16 表示。第一个值为 <code>U+D83D</code> (十进制值为 55357),第二个值为 <code>U+DC36</code> (十进制值为 56374)。</p>
<h5 id="unicode-scalars-">Unicode 标量 (Scalars)</h5>
<p>您可以通过遍历字符串的 <code>unicodeScalars</code> 属性来访问它的 Unicode 标量表示。其为 <strong>UnicodeScalarView</strong> 类型的属性, <strong>UnicodeScalarView</strong><code>UnicodeScalar</code> 的集合。<code>UnicodeScalar</code> 是21位的 Unicode 代码点。</p>
<p>每一个 <code>UnicodeScalar</code> 拥有一个值属性可以返回对应的21位数值<code>UInt32</code> 来表示。</p>
<pre><code>for scalar in dogString.unicodeScalars {
print(&quot;\(scalar.value) &quot;)
}
print(&quot;\n&quot;)
// 68 111 103 33 128054
</code></pre><p>同样,前四个代码单元值 (68, 111, 103, 33) 代表了字符 <code>D</code> <code>o</code> <code>g</code><code>!</code> 。第五位数值128054是一个十六进制1F436的十进制表示。其等同于 <code>狗脸表情</code> 的Unicode 标量 U+1F436。</p>
<p>作为查询字符值属性的一种替代方法,每个 <code>UnicodeScalar</code> 值也可以用来构建一个新的字符串值,比如在字符串插值中使用:</p>
<pre><code>for scalar in dogString.unicodeScalars {
println(&quot;\(scalar) &quot;)
}
// D
// o
// g
// !
// 🐶
</code></pre>
</section>
</div>
</div>
</div>
<a href="../chapter2/basic_operators.html" class="navigation navigation-prev navigation-unique" aria-label="Previous page: 基本操作符"><i class="fa fa-angle-left"></i></a>
</div>
</div>
<script src="http://cdn.bootcss.com/ace/1.1.3/ace.js"></script>
<script src="http://cdn.bootcss.com/ace/1.1.3/mode-javascript.js"></script>
<script src="../gitbook/jsrepl/jsrepl.js" id="jsrepl-script"></script>
<script src="../gitbook/app.js"></script>
<script src="../gitbook/plugins/gitbook-plugin-mixpanel/plugin.js"></script>
<script src="http://cdn.mathjax.org/mathjax/2.0-latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script src="../gitbook/plugins/gitbook-plugin-mathjax/plugin.js"></script>
<script>
require(["gitbook"], function(gitbook) {
var config = {};
gitbook.start(config);
});
</script>
</body>
</html>

View File

@ -46,7 +46,7 @@
<div class="book" data-level="2" data-basepath=".." data-revision="1401895096940">
<div class="book" data-level="2" data-basepath=".." data-revision="1401919801865">
<div class="book-header">
<!-- Actions Left -->
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
@ -173,6 +173,24 @@
</a>
</li>
<li class="chapter " data-level="2.2" data-path="chapter2/basic_operators.html">
<a href="../chapter2/basic_operators.html">
<i class="fa fa-check"></i> <b>2.2.</b> 基本操作符
</a>
</li>
<li class="chapter " data-level="2.3" data-path="chapter2/strings_and_characters.html">
<a href="../chapter2/strings_and_characters.html">
<i class="fa fa-check"></i> <b>2.3.</b> 字符串和字符
</a>
</li>
@ -197,28 +215,32 @@
<div class="page-wrapper" tabindex="-1">
<div class="book-progress">
<div class="bar">
<div class="inner" style="width: 80%;min-width: 60%;"></div>
<div class="inner" style="width: 57.142857142857146%;min-width: 42.857142857142854%;"></div>
</div>
<div class="chapters">
<a href="../index.html" title="Introduction" class="chapter done new-chapter" data-progress="0" style="left: 0%;"></a>
<a href="../chapter1/README.html" title="欢迎使用 Swift" class="chapter done new-chapter" data-progress="1" style="left: 20%;"></a>
<a href="../chapter1/README.html" title="欢迎使用 Swift" class="chapter done new-chapter" data-progress="1" style="left: 14.285714285714286%;"></a>
<a href="../chapter1/swift.html" title="关于 Swift" class="chapter done " data-progress="1.1" style="left: 40%;"></a>
<a href="../chapter1/swift.html" title="关于 Swift" class="chapter done " data-progress="1.1" style="left: 28.571428571428573%;"></a>
<a href="../chapter1/a_swift_tour.html" title="Swift 初见" class="chapter done " data-progress="1.2" style="left: 60%;"></a>
<a href="../chapter1/a_swift_tour.html" title="Swift 初见" class="chapter done " data-progress="1.2" style="left: 42.857142857142854%;"></a>
<a href="../chapter2/the_basics.html" title="Swift 教程" class="chapter done new-chapter" data-progress="2" style="left: 80%;"></a>
<a href="../chapter2/the_basics.html" title="Swift 教程" class="chapter done new-chapter" data-progress="2" style="left: 57.142857142857146%;"></a>
<a href="../chapter2/article_1.html" title="基础部分" class="chapter " data-progress="2.1" style="left: 100%;"></a>
<a href="../chapter2/article_1.html" title="基础部分" class="chapter " data-progress="2.1" style="left: 71.42857142857143%;"></a>
<a href="../chapter2/basic_operators.html" title="基本操作符" class="chapter " data-progress="2.2" style="left: 85.71428571428571%;"></a>
<a href="../chapter2/strings_and_characters.html" title="字符串和字符" class="chapter " data-progress="2.3" style="left: 100%;"></a>
</div>
</div>
<div class="page-inner">
<section class="normal" id="section-gitbook_17">
<section class="normal" id="section-gitbook_12">
<h1 id="swift-">Swift 教程</h1>
<p>本章介绍了 Swift 的各种特性及其使用方法,是全书的核心部分。</p>

View File

@ -44,7 +44,7 @@
<div class="book" data-level="0" data-basepath="." data-revision="1401895096940">
<div class="book" data-level="0" data-basepath="." data-revision="1401919801865">
<div class="book-header">
<!-- Actions Left -->
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
@ -171,6 +171,24 @@
</a>
</li>
<li class="chapter " data-level="2.2" data-path="chapter2/basic_operators.html">
<a href="./chapter2/basic_operators.html">
<i class="fa fa-check"></i> <b>2.2.</b> 基本操作符
</a>
</li>
<li class="chapter " data-level="2.3" data-path="chapter2/strings_and_characters.html">
<a href="./chapter2/strings_and_characters.html">
<i class="fa fa-check"></i> <b>2.3.</b> 字符串和字符
</a>
</li>
@ -201,22 +219,26 @@
<a href="./index.html" title="Introduction" class="chapter done new-chapter" data-progress="0" style="left: 0%;"></a>
<a href="./chapter1/README.html" title="欢迎使用 Swift" class="chapter new-chapter" data-progress="1" style="left: 20%;"></a>
<a href="./chapter1/README.html" title="欢迎使用 Swift" class="chapter new-chapter" data-progress="1" style="left: 14.285714285714286%;"></a>
<a href="./chapter1/swift.html" title="关于 Swift" class="chapter " data-progress="1.1" style="left: 40%;"></a>
<a href="./chapter1/swift.html" title="关于 Swift" class="chapter " data-progress="1.1" style="left: 28.571428571428573%;"></a>
<a href="./chapter1/a_swift_tour.html" title="Swift 初见" class="chapter " data-progress="1.2" style="left: 60%;"></a>
<a href="./chapter1/a_swift_tour.html" title="Swift 初见" class="chapter " data-progress="1.2" style="left: 42.857142857142854%;"></a>
<a href="./chapter2/the_basics.html" title="Swift 教程" class="chapter new-chapter" data-progress="2" style="left: 80%;"></a>
<a href="./chapter2/the_basics.html" title="Swift 教程" class="chapter new-chapter" data-progress="2" style="left: 57.142857142857146%;"></a>
<a href="./chapter2/article_1.html" title="基础部分" class="chapter " data-progress="2.1" style="left: 100%;"></a>
<a href="./chapter2/article_1.html" title="基础部分" class="chapter " data-progress="2.1" style="left: 71.42857142857143%;"></a>
<a href="./chapter2/basic_operators.html" title="基本操作符" class="chapter " data-progress="2.2" style="left: 85.71428571428571%;"></a>
<a href="./chapter2/strings_and_characters.html" title="字符串和字符" class="chapter " data-progress="2.3" style="left: 100%;"></a>
</div>
</div>
<div class="page-inner">
<section class="normal" id="section-gitbook_12">
<section class="normal" id="section-gitbook_5">
<h1 id="swift-">Swift 编程语言</h1>
<p>Swift 是苹果在 WWDC 2014 上发布的一款全新的编程语言,本书译自苹果官方的 Swift 教程《The Swift Programming Language》。</p>
@ -267,4 +289,3 @@ require(["gitbook"], function(gitbook) {
</body>
</html>
</html>

View File

@ -1,5 +1,5 @@
CACHE MANIFEST
# Revision 1401895096943
# Revision 1401919801866
CACHE:
index.html
@ -7,6 +7,8 @@ chapter1/README.html
chapter1/a_swift_tour.html
chapter1/swift.html
chapter2/article_1.html
chapter2/basic_operators.html
chapter2/strings_and_characters.html
chapter2/the_basics.html
gitbook/app.js
gitbook/fonts/anonymouspro/400.woff

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,339 @@
# 字符串和字符 (Strings and Characters)
**String** 是一个有序的字符集合,例如 "hello, world", "albatross"。Swift 字符串通过 **String** 类型来表示,也可以表示为 **Character** 类型值的集合。
Swift 的 **String****Character** 类型提供了一个快速的,兼容 Unicode 的方式来处理代码中的文本信息。创建和操作字符串的语法与 C的操作方式相似轻量并且易读。字符串连接操作只需要简单地通过 `+` 号将两个字符串相连即可。与 Swift 中其他值一样,能否更改字符串的值,取决于其被定义为常量还是变量。
尽管语法简易,但 **String** 类型是一种快速、现代化的字符串实现。每一个字符串都是由独立编码的 Unicode 字符组成并提供了用于访问这些字符在不同的Unicode表示的支持。
**String** 也可以用于在常量、变量、字面量和表达式中进行字符串插值,这使得创建用于展示、存储和打印的字符串变得轻松自如。
> 注意:
>
> Swift 的 **String** 类型与 Foundation NSString 类进行了无缝桥接。如果您利用 Cocoa 或 Cocoa Touch 中的 Foundation 框架进行工作,整个 NSString API 都可以调用您创建的任意 String 类型的值,您额外还可以在任意 API 中使用本章介绍的 **String** 特性。您也可以在任意要求传入NSString 实例作为参数的 API 中使用 **String** 类型的值进行替换。
>
>更多关于在 Foundation 和 Cocoa 中使用 **String** 的信息请查看 [Using Swift with Cocoa and Objective-C](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/index.html#//apple_ref/doc/uid/TP40014216)。
### 字符串字面量
您可以在您的代码中包含一段预定义的字符串值作为字符串字面量。字符串字面量是由双引号包裹着的具有固定顺序的文本字符集。
字符串字面量可以用于为常量和变量提供初始值。
```
let someString = "Some string literal value"
```
> 注意:
>
> `someString` 变量通过字符串字面量进行初始化Swift 因此推断其为 **String** 类型。
字符串字面量可以包含以下特殊字符:
* 转移特殊字符 `\0` (空字符)、`\\`(反斜线)、`\t` (水平制表符)、`\n` (换行符)、`\r` (回车符)、`\"` (双引号)、`\'` (单引号)。
* 单字节 Unicode 标量,写成 `\xnn`,其中 nn 为两位十六进制数。
* 双字节 Unicode 标量,写成 `\unnnn`,其中 nnnn 为四位十六进制数。
* 四字节 Unicode 标量,写成 `\Unnnnnnnn`,其中 nnnnnnnn 为八位十六进制数。
下面的代码为各种特殊字符的使用示例。
`wiseWords` 常量包含了两个转移特殊字符 (双括号)`dollarSign``blackHeart``sparklingHeart` 常量演示了三种不同格式的 Unicode 标量:
```
let wiseWords = "\"Imagination is more important than knowledge\" - Einstein"
// "Imagination is more important than knowledge" - Einstein
let dollarSign = "\x24" // $, Unicode scalar U+0024
let blackHeart = "\u2665" // ♥, Unicode scalar U+2665
let sparklingHeart = "\U0001F496" // 💖, Unicode scalar U+1F496
```
### 初始化空字符串
为了构造一个很长的字符串,可以创建一个空字符串作为初始值。可以将空的字符串字面量赋值给变量,也可以初始化一个新的 **String** 实例:
```
var emptyString = "" // empty string literal
var anotherEmptyString = String() // initializer syntax
// 这两个字符串都为空,并且两者等价
```
您可以通过检查其 **Boolean** 类型的 `isEmpty` 属性来判断该字符串是否为空:
```
if emptyString.isEmpty {
println("Nothing to see here")
}
// 打印 "Nothing to see here"
```
### 字符串可变性
您可以通过将一个特定字符串分配给一个变量来对其进行修改,或者分配给一个常量来保证其不会被修改:
```
var variableString = "Horse"
variableString += " and carriage"
// variableString 现在为 "Horse and carriage"
let constantString = "Highlander"
constantString += " and another Highlander"
// 这会报告一个编译错误(compile-time error) - 常量不可以被修改。
```
> 注意:
>
> 在 Objective-C 和 Cocoa 中,您通过选择两个不同的类( NSString 和 NSMutableString )来指定该字符串是否可以被修改Swift中的字符串是否可以修改仅通过定义的是变量还是常量来决定实现了多种类型可变性操作的统一。
### 字符串是值类型
Swift 的 **String** 类型是值类型。如果您创建了一个新的字符串,那么当其进行常量、变量赋值操作或在函数/方法中传递时,会进行值拷贝。任何情况下,都会对已有字符串值创建新副本,并对该新副本进行传递或赋值。值类型在 [Structures and Enumerations Are Value Types](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ClassesAndStructures.html#//apple_ref/doc/uid/TP40014097-CH13-XID_104) 中进行了说明。
> 注意:
>
> 其 Cocoa 中的 NSString 不同,当您在 Cocoa 中创建了一个 NSString 实例,并将其传递给一个函数/方法,或者赋值给一个变量,您永远都是传递或赋值同一个 NSString 实例的一个引用。除非您特别要求其进行值拷贝,否则字符串不会进行赋值新副本操作。
Swift 默认字符串拷贝的方式保证了在函数/方法中传递的是字符串的值,其明确了无论该值来自于哪里,都是您独自拥有的。您可以放心您传递的字符串本身不会被更改。
在实际编译时Swift编译器会优化字符串的使用使实际的复制只发生在绝对必要的情况下这意味着您始终可以将字符串作为值类型的同时获得极高的性能。
#### 使用字符(Characters)
Swift 的 **String** 类型表示特定序列的字符值的集合。每一个字符值代表一个 Unicode 字符。您可利用 for-in 循环来遍历字符串中的每一个字符:
```
for character in "Dog!🐶" {
println(character)
}
// D
// o
// g
// !
// 🐶
```
for-in 循环在[For Loops](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ControlFlow.html#//apple_ref/doc/uid/TP40014097-CH9-XID_154)中进行了详细描述。
另外,通过标明一个 **Character** 类型注解并通过字符字面量进行赋值,可以建立一个独立的字符常量或变量:
```
let yenSign: Character = "¥"
```
### 计算字符数量
通过调用全局 `countElements` 函数并将字符串作为参数进行传递可以获取该字符串的字符数量。
```
let unusualMenagerie = "Koala 🐨, Snail 🐌, Penguin 🐧, Dromedary 🐪"
println("unusualMenagerie has \(countElements(unusualMenagerie)) characters")
// prints "unusualMenagerie has 40 characters"
```
>注意:
>
>不同的 Unicode 字符以及相同 Unicode 字符的不同表示方式可能需要不同数量的内存空间来存储所以Swift 中的字符在一个字符串中并不一定占用相同的内存空间。因此,字符串的长度不得不通过迭代字符串中每一个字符的长度来进行计算。如果您正在处理一个长字符串,需要注意 `countElements` 函数必须遍历字符串中的字符以精准计算字符串的长度。
>
>另外需要注意的是通过 `countElements` 返回的字符数量并不总是与包含相同字符的 NSString 的 `length` 属性相同。NSString 的 `length` 属性是基于利用 UTF-16 表示的十六位代码单元数字,而不是基于 Unicode 字符。为了解决这个问题NSString 的 `length` 属性在被 Swift的 **String** 访问时会成为 `utf16count`。
### 连接字符串和字符
字符串和字符的值可以通过加法运算符 (+) 相加在一起并创建一个新的字符串值:
```
let string1 = "hello"
let string2 = " there"
let character1: Character = "!"
let character2: Character = "?"
let stringPlusCharacter = string1 + character1 // 等于 "hello!"
let stringPlusString = string1 + string2 // 等于 "hello there"
let characterPlusString = character1 + string1 // 等于 "!hello"
let characterPlusCharacter = character1 + character2 // 等于 "!?"
```
您也可以通过加法赋值运算符 (+=) 将一个字符串或者字符添加到一个已经存在字符串变量上:
```
var instruction = "look over"
instruction += string2
// instruction 现在等于 "look over there"
var welcome = "good morning"
welcome += character1
// welcome 现在等于 "good morning!"
```
>注意:
>
>您不能将一个字符串或者字符添加到一个已经存在的字符变量上,因为字符变量只能包含一个字符。
### 字符串插值
字符串插值是一种全新的构建字符串的方式,可以在其中包含常量、变量、字面量和表达式。您插入的字符串字面量的每一项都被包裹在以反斜线为前缀的圆括号中:
```
let multiplier = 3
let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"
// message is "3 times 2.5 is 7.5"
```
在上面的例子中,`multiplier` 作为 `\(multiplier)` 被插入到一个字符串字面量中。当创建字符串执行插值计算时此占位符会被替换为 `multiplier` 实际的值。
`multiplier` 的值也作为字符串中后面表达式的一部分。该表达式计算 `Double(multiplier) * 2.5` 的值并将结果 (7.5) 插入到字符串中。在这个例子中,表达式写为 `\(Double(multiplier) * 2.5)` 并包含在字符串字面量中。
>注意:
>
>您插值字符串中写在括号中的表达式不能包含非转义双引号 (") 和反斜杠 (\\),并且不能包含回车或换行符。
### 比较字符串
Swift 提供了三种方式来比较字符串的值:字符串相等,前缀相等和后缀相等。
##### 字符串相等
如果两个字符串以同一顺序包含完全相同的字符,则认为两者字符串相等:
```
let quotation = "We're a lot alike, you and I."
let sameQuotation = "We're a lot alike, you and I."
if quotation == sameQuotation {
println("These two strings are considered equal")
}
// prints "These two strings are considered equal"
```
##### 前缀/后缀相等
通过调用字符串的 `hasPrefix`/`hasSuffix` 方法来检查字符串是否拥有特定前缀/后缀。两个方法均需要以字符串作为参数传入并传出 **Boolean** 值。两个方法均执行基本字符串和前缀/后缀字符串之间逐个字符的比较操作。
下面的例子以一个字符串数组表示莎士比亚话剧 `罗密欧与朱丽叶` 中前两场的场景位置:
```
let romeoAndJuliet = [
"Act 1 Scene 1: Verona, A public place",
"Act 1 Scene 2: Capulet's mansion",
"Act 1 Scene 3: A room in Capulet's mansion",
"Act 1 Scene 4: A street outside Capulet's mansion",
"Act 1 Scene 5: The Great Hall in Capulet's mansion",
"Act 2 Scene 1: Outside Capulet's mansion",
"Act 2 Scene 2: Capulet's orchard",
"Act 2 Scene 3: Outside Friar Lawrence's cell",
"Act 2 Scene 4: A street in Verona",
"Act 2 Scene 5: Capulet's mansion",
"Act 2 Scene 6: Friar Lawrence's cell"
]
```
您可以利用 `hasPrefix` 方法来计算话剧中第一幕的场景数:
```
var act1SceneCount = 0
for scene in romeoAndJuliet {
if scene.hasPrefix("Act 1 ") {
++act1SceneCount
}
}
println("There are \(act1SceneCount) scenes in Act 1")
// prints "There are 5 scenes in Act 1"
```
##### 大写和小写字符串
您可以通过字符串的 `uppercaseString``lowercaseString` 属性来访问一个字符串的大写/小写版本。
```
let normal = "Could you help me, please?"
let shouty = normal.uppercaseString
// shouty 值为 "COULD YOU HELP ME, PLEASE?"
let whispered = normal.lowercaseString
// whispered 值为 "could you help me, please?"
```
### Unicode
Unicode 是文本编码和表示的国际标准。它使您可以用标准格式表示来自任意语言几乎所有的字符,并能够对文本文件或网页这样的外部资源中的字符进行读写操作。
Swift 的字符串和字符类型是完全兼容 Unicode 的,它支持如下所述的一系列不同的 Unicode 编码。
###### Unicode 术语(Terminology)
Unicode 中每一个字符都可以被解释为一个或多个 unicode 标量。字符的 unicode 标量是一个唯一的21位数字(和名称),例如 `U+0061` 表示小写的拉丁字母A ("a")`U+1F425` 表示正面站立的鸡宝宝 ("🐥")
当 Unicode 字符串被写进文本文件或其他存储结构当中,这些 unicode 标量将会按照 Unicode 定义的集中格式之一进行编码。其包括 `UTF-8` (以8位代码单元进行编码) 和 `UTF-16` (以16位代码单元进行编码)。
##### 字符串的 Unicode 表示
Swift 提供了几种不同的方式来访问字符串的 Unicode 表示。
您可以利用 `for-in` 来对字符串进行遍历,从而以 Unicode 字符的方式访问每一个字符值。该过程在 [Working with Characters](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/StringsAndCharacters.html#//apple_ref/doc/uid/TP40014097-CH7-XID_376) 中进行了描述。
另外,能够以其他三种 Unicode 兼容的方式访问字符串的值:
* UTF-8 代码单元集合 (利用字符串的 `utf8` 属性进行访问)
* UTF-16 代码单元集合 (利用字符串的 `utf16` 属性进行访问)
* 21位的 Unicode 标量值集合 (利用字符串的 `unicodeScalars` 属性进行访问)
下面由 `D` `o` `g` `!``🐶` (狗脸表情Unicode 标量为 `U+1F436`)组成的字符串中的每一个字符代表着一种不同的表示:
```
let dogString = "Dog!🐶"
```
##### UTF-8
您可以通过遍历字符串的 `utf8` 属性来访问它的 `UTF-8` 表示。其为 **UTF8View** 类型的属性,**UTF8View** 是无符号8位 (`UInt8`) 值的集合,每一个 `UIn8` 都是一个字符的 UTF-8 表示:
```
for codeUnit in dogString.utf8 {
print("\(codeUnit) ")
}
print("\n")
// 68 111 103 33 240 159 144 182
```
上面的例子中前四个10进制代码单元值 (68, 111, 103, 33) 代表了字符 `D` `o` `g``!` ,他们的 UTF-8 表示与 ASCII 表示相同。后四个代码单元值 (240, 159, 144, 182) 是 `狗脸表情` 的4位 UTF-8 表示。
##### UTF-16
您可以通过遍历字符串的 `utf16` 属性来访问它的 `UTF-16` 表示。其为 **UTF16View** 类型的属性,**UTF16View** 是无符号16位 (`UInt16`) 值的集合,每一个 `UInt16` 都是一个字符的 UTF-16 表示:
```
for codeUnit in dogString.utf16 {
print("\(codeUnit) ")
}
print("\n")
// 68 111 103 33 55357 56374
```
同样,前四个代码单元值 (68, 111, 103, 33) 代表了字符 `D` `o` `g``!` ,他们的 UTF-16 代码单元和 UTF-8 完全相同。
第五和第六个代码单元值 (55357 and 56374) 是 `狗脸表情` 字符的UTF-16 表示。第一个值为 `U+D83D` (十进制值为 55357),第二个值为 `U+DC36` (十进制值为 56374)。
##### Unicode 标量 (Scalars)
您可以通过遍历字符串的 `unicodeScalars` 属性来访问它的 Unicode 标量表示。其为 **UnicodeScalarView** 类型的属性, **UnicodeScalarView**`UnicodeScalar` 的集合。`UnicodeScalar` 是21位的 Unicode 代码点。
每一个 `UnicodeScalar` 拥有一个值属性可以返回对应的21位数值`UInt32` 来表示。
```
for scalar in dogString.unicodeScalars {
print("\(scalar.value) ")
}
print("\n")
// 68 111 103 33 128054
```
同样,前四个代码单元值 (68, 111, 103, 33) 代表了字符 `D` `o` `g``!` 。第五位数值128054是一个十六进制1F436的十进制表示。其等同于 `狗脸表情` 的Unicode 标量 U+1F436。
作为查询字符值属性的一种替代方法,每个 `UnicodeScalar` 值也可以用来构建一个新的字符串值,比如在字符串插值中使用:
```
for scalar in dogString.unicodeScalars {
println("\(scalar) ")
}
// D
// o
// g
// !
// 🐶
```