make gitbook
This commit is contained in:
17
chapter1/01_swift.html
Executable file → Normal file
17
chapter1/01_swift.html
Executable file → Normal file
@ -46,7 +46,7 @@
|
||||
|
||||
|
||||
|
||||
<div class="book" data-level="1.1" data-basepath=".." data-revision="1402677669306">
|
||||
<div class="book" data-level="1.1" data-basepath=".." data-revision="1402750255397">
|
||||
<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>
|
||||
@ -268,7 +268,7 @@
|
||||
<li class="chapter " data-level="2.12" data-path="chapter2/12_Subscripts.html">
|
||||
|
||||
<a href="../chapter2/12_Subscripts.html">
|
||||
<i class="fa fa-check"></i> <b>2.12.</b> 附属脚本
|
||||
<i class="fa fa-check"></i> <b>2.12.</b> 下标脚本
|
||||
</a>
|
||||
|
||||
|
||||
@ -520,7 +520,7 @@
|
||||
|
||||
<a href="../chapter2/11_Methods.html" title="方法" class="chapter " data-progress="2.11" style="left: 18.42105263157895%;"></a>
|
||||
|
||||
<a href="../chapter2/12_Subscripts.html" title="附属脚本" class="chapter " data-progress="2.12" style="left: 21.05263157894737%;"></a>
|
||||
<a href="../chapter2/12_Subscripts.html" title="下标脚本" class="chapter " data-progress="2.12" style="left: 21.05263157894737%;"></a>
|
||||
|
||||
<a href="../chapter2/13_Inheritance.html" title="继承" class="chapter " data-progress="2.13" style="left: 23.68421052631579%;"></a>
|
||||
|
||||
@ -587,20 +587,19 @@
|
||||
|
||||
<div class="page-inner">
|
||||
|
||||
<section class="normal" id="section-gitbook_83">
|
||||
<section class="normal" id="section-gitbook_30">
|
||||
|
||||
<blockquote>
|
||||
<p>翻译:numbbbbb</p>
|
||||
<p>校对:yeahdongcn</p>
|
||||
<p>翻译:numbbbbb<br>校对:yeahdongcn</p>
|
||||
</blockquote>
|
||||
<h1 id="-swift">关于 Swift</h1>
|
||||
<hr>
|
||||
<p>Swift 是一种新的编程语言,用于编写 iOS 和 OS X 应用。Swift 结合了 C 和 Objective-C 的优点并且不受C兼容性的限制。Swift 采用安全的编程模式并添加了很多新特性,这将使编程更简单,更灵活,也更有趣。Swift 是基于成熟而且倍受喜爱的 Cocoa 和 Cocoa Touch 框架,他的降临将重新定义软件开发。</p>
|
||||
<p>Swift 的开发从很久之前就开始了。为了给 Swift 打好基础,苹果公司改进了编译器,调试器和框架结构。我们使用自动引用计数(Automatic Reference Counting, ARC)来简化内存管理。我们在 Foundation 和 Cocoa的基础上构建框架栈并将其标准化。Objective-C 本身支持块、集合语法和模块,所以框架可以轻松支持现代编程语言技术。正是得益于这些基础工作,我们现在才能发布这样一个用于未来苹果软件开发的新语言。</p>
|
||||
<p>Swift 是一种新的编程语言,用于编写 iOS 和 OS X 应用。Swift 结合了 C 和 Objective-C 的优点并且不受 C 兼容性的限制。Swift 采用安全的编程模式并添加了很多新特性,这将使编程更简单,更灵活,也更有趣。Swift 是基于成熟而且倍受喜爱的 Cocoa 和 Cocoa Touch 框架,它的降临将重新定义软件开发。</p>
|
||||
<p>Swift 的开发从很久之前就开始了。为了给 Swift 打好基础,苹果公司改进了编译器,调试器和框架结构。我们使用自动引用计数(Automatic Reference Counting, ARC)来简化内存管理。我们在 Foundation 和 Cocoa 的基础上构建框架栈并将其标准化。Objective-C 本身支持块、集合语法和模块,所以框架可以轻松支持现代编程语言技术。正是得益于这些基础工作,我们现在才能发布这样一个用于未来苹果软件开发的新语言。</p>
|
||||
<p>Objective-C 开发者对 Swift 并不会感到陌生。它采用了 Objective-C 的命名参数以及动态对象模型,可以无缝对接到现有的 Cocoa 框架,并且可以兼容 Objective-C 代码。在此基础之上,Swift 还有许多新特性并且支持过程式编程和面向对象编程。</p>
|
||||
<p>Swift 对于初学者来说也很友好。它是第一个既满足工业标准又像脚本语言一样充满表现力和趣味的编程语言。它支持代码预览,这个革命性的特性可以允许程序员在不编译和运行应用程序的前提下运行 Swift 代码并实时查看结果。</p>
|
||||
<p>Swift 将现代编程语言的精华和苹果工程师文化的智慧结合了起来。编译器对性能进行了优化,编程语言对开发进行了优化,两者互不干扰,鱼与熊掌兼得。Swift 既可以用于开发 “hello, world” 这样的小程序,也可以用于开发一套完整的操作系统。所有的这些特性让 Swift 对于开发者和苹果来说都是一项值得的投资。</p>
|
||||
<p>用 Swift 编写 iOS 和 OS X 应用将是一场美妙的体验,Swift 之后也会不断开发新特性和兼容性。我们对 Swift 充满信心,你还在等什么!</p>
|
||||
<p>Swift 是编写 iOS 和 OS X 应用的极佳手段,并将伴随着新的特性和功能持续演进。我们对 Swift 充满信心,你还在等什么!</p>
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
754
chapter1/02_a_swift_tour.html
Executable file → Normal file
754
chapter1/02_a_swift_tour.html
Executable file → Normal file
@ -46,7 +46,7 @@
|
||||
|
||||
|
||||
|
||||
<div class="book" data-level="1.2" data-basepath=".." data-revision="1402677669306">
|
||||
<div class="book" data-level="1.2" data-basepath=".." data-revision="1402750255397">
|
||||
<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>
|
||||
@ -268,7 +268,7 @@
|
||||
<li class="chapter " data-level="2.12" data-path="chapter2/12_Subscripts.html">
|
||||
|
||||
<a href="../chapter2/12_Subscripts.html">
|
||||
<i class="fa fa-check"></i> <b>2.12.</b> 附属脚本
|
||||
<i class="fa fa-check"></i> <b>2.12.</b> 下标脚本
|
||||
</a>
|
||||
|
||||
|
||||
@ -520,7 +520,7 @@
|
||||
|
||||
<a href="../chapter2/11_Methods.html" title="方法" class="chapter " data-progress="2.11" style="left: 18.42105263157895%;"></a>
|
||||
|
||||
<a href="../chapter2/12_Subscripts.html" title="附属脚本" class="chapter " data-progress="2.12" style="left: 21.05263157894737%;"></a>
|
||||
<a href="../chapter2/12_Subscripts.html" title="下标脚本" class="chapter " data-progress="2.12" style="left: 21.05263157894737%;"></a>
|
||||
|
||||
<a href="../chapter2/13_Inheritance.html" title="继承" class="chapter " data-progress="2.13" style="left: 23.68421052631579%;"></a>
|
||||
|
||||
@ -587,11 +587,10 @@
|
||||
|
||||
<div class="page-inner">
|
||||
|
||||
<section class="normal" id="section-gitbook_85">
|
||||
<section class="normal" id="section-gitbook_32">
|
||||
|
||||
<blockquote>
|
||||
<p>翻译:numbbbbb
|
||||
校对:shinyzhu</p>
|
||||
<p>翻译:numbbbbb<br>校对:shinyzhu, stanzhai</p>
|
||||
</blockquote>
|
||||
<h1 id="swift-">Swift 初见</h1>
|
||||
<hr>
|
||||
@ -602,341 +601,329 @@
|
||||
<li><a href="#functions_and_closures">函数和闭包(Functions and Closures)</a></li>
|
||||
<li><a href="#objects_and_classes">对象和类(Objects and Classes)</a></li>
|
||||
<li><a href="#enumerations_and_structures">枚举和结构体(Enumerations and Structures)</a></li>
|
||||
<li><a href="#protocols_and_extensions">接口和扩展(Protocols and Extensions)</a></li>
|
||||
<li><a href="#protocols_and_extensions">协议和扩展(Protocols and Extensions)</a></li>
|
||||
<li><a href="#generics">泛型(Generics)</a></li>
|
||||
</ul>
|
||||
<p>通常来说,编程语言教程中的第一个程序应该在屏幕上打印“Hello, world”。在 Swift 中,可以用一行代码实现:</p>
|
||||
<pre><code class="lang-swift"> println("Hello, world")
|
||||
<pre><code class="lang-swift">println("Hello, world")
|
||||
</code></pre>
|
||||
<p>如果你写过 C 或者 Objective-C 代码,那你应该很熟悉这种形式——在 Swift 中,这行代码就是一个完整的程序。你不需要为了输入输出或者字符串处理导入一个单独的库。全局作用域中的代码会被自动当做程序的入口点,所以你也不需要<code>main</code>函数。你同样不需要在每个语句结尾写上分号。</p>
|
||||
<p>这个教程会通过一系列编程例子来让你对 Swift 有初步了解,如果你有什么不理解的地方也不用担心——任何本章介绍的内容都会在后面的章节中详细讲解。</p>
|
||||
<blockquote>
|
||||
<p>注意:</p>
|
||||
<p>为了获得最好的体验,在 Xcode 当中使用代码预览功能。代码预览功能可以让你编辑代码并实时看到运行结果。</p>
|
||||
<p>注意:<br>为了获得最好的体验,在 Xcode 当中使用代码预览功能。代码预览功能可以让你编辑代码并实时看到运行结果。</p>
|
||||
</blockquote>
|
||||
<p><a name="simple_values"></a></p>
|
||||
<h2 id="-">简单值</h2>
|
||||
<p>使用<code>let</code>来声明常量,使用<code>var</code>来声明变量。一个常量的值在编译时并不需要获取,但是你只能为它赋值一次。也就是说你可以用常量来表示这样一个值:你只需要决定一次,但是需要使用很多次。</p>
|
||||
<pre><code class="lang-swift"> var myVariable = 42
|
||||
myVariable = 50
|
||||
let myConstant = 42
|
||||
<p>使用<code>let</code>来声明常量,使用<code>var</code>来声明变量。一个常量的值,在编译的时候,并不需要有明确的值,但是你只能为它赋值一次。也就是说你可以用常量来表示这样一个值:你只需要决定一次,但是需要使用很多次。</p>
|
||||
<pre><code class="lang-swift">var myVariable = 42
|
||||
myVariable = 50
|
||||
let myConstant = 42
|
||||
</code></pre>
|
||||
<p>常量或者变量的类型必须和你赋给它们的值一样。然而,声明时类型是可选的,声明的同时赋值的话,编译器会自动推断类型。在上面的例子中,编译器推断出<code>myVariable</code>是一个整数(integer)因为它的初始值是整数。</p>
|
||||
<p>如果初始值没有提供足够的信息(或者没有初始值),那你需要在变量后面声明类型,用冒号分割。</p>
|
||||
<pre><code class="lang-swift"> let implicitInteger = 70
|
||||
let implicitDouble = 70.0
|
||||
let explicitDouble: Double = 70
|
||||
<pre><code class="lang-swift">let implicitInteger = 70
|
||||
let implicitDouble = 70.0
|
||||
let explicitDouble: Double = 70
|
||||
</code></pre>
|
||||
<blockquote>
|
||||
<p>练习:</p>
|
||||
<p>创建一个常量,显式指定类型为<code>Float</code>并指定初始值为4。</p>
|
||||
<p>练习:<br>创建一个常量,显式指定类型为<code>Float</code>并指定初始值为4。</p>
|
||||
</blockquote>
|
||||
<p>值永远不会被隐式转换为其他类型。如果你需要把一个值转换成其他类型,请显式转换。</p>
|
||||
<pre><code class="lang-swift"> let label = "The width is"
|
||||
let width = 94
|
||||
let widthLabel = label + String(width)
|
||||
<pre><code class="lang-swift">let label = "The width is"
|
||||
let width = 94
|
||||
let widthLabel = label + String(width)
|
||||
</code></pre>
|
||||
<blockquote>
|
||||
<p>练习:</p>
|
||||
<p>删除最后一行中的<code>String</code>,错误提示是什么?</p>
|
||||
<p>练习:<br>删除最后一行中的<code>String</code>,错误提示是什么?</p>
|
||||
</blockquote>
|
||||
<p>有一种更简单的把值转换成字符串的方法:把值写到括号中,并且在括号之前写一个反斜杠。例如:</p>
|
||||
<pre><code class="lang-swift"> let apples = 3
|
||||
let oranges = 5
|
||||
let appleSummary = "I have \(apples) apples."
|
||||
let fruitSummary = "I have \(apples + oranges) pieces of fruit."
|
||||
<pre><code class="lang-swift">let apples = 3
|
||||
let oranges = 5
|
||||
let appleSummary = "I have \(apples) apples."
|
||||
let fruitSummary = "I have \(apples + oranges) pieces of fruit."
|
||||
</code></pre>
|
||||
<blockquote>
|
||||
<p>练习:</p>
|
||||
<p>使用<code>\()</code>来把一个浮点计算转换成字符串,并加上某人的名字,和他打个招呼。</p>
|
||||
<p>练习:<br>使用<code>\()</code>来把一个浮点计算转换成字符串,并加上某人的名字,和他打个招呼。</p>
|
||||
</blockquote>
|
||||
<p>使用方括号<code>[]</code>来创建数组和字典,并使用下标或者键(key)来访问元素。</p>
|
||||
<pre><code class="lang-swift"> var shoppingList = ["catfish", "water", "tulips", "blue paint"]
|
||||
shoppingList[1] = "bottle of water"
|
||||
<pre><code class="lang-swift">var shoppingList = ["catfish", "water", "tulips", "blue paint"]
|
||||
shoppingList[1] = "bottle of water"
|
||||
</code></pre>
|
||||
<pre><code class="lang-swift"> var occupations = [
|
||||
"Malcolm": "Captain",
|
||||
"Kaylee": "Mechanic",
|
||||
]
|
||||
occupations["Jayne"] = "Public Relations"
|
||||
<pre><code class="lang-swift">var occupations = [
|
||||
"Malcolm": "Captain",
|
||||
"Kaylee": "Mechanic",
|
||||
]
|
||||
occupations["Jayne"] = "Public Relations"
|
||||
</code></pre>
|
||||
<p>要创建一个空数组或者字典,使用初始化语法。</p>
|
||||
<pre><code class="lang-swift"> let emptyArray = String[]()
|
||||
let emptyDictionary = Dictionary<String, Float>()
|
||||
<pre><code class="lang-swift">let emptyArray = String[]()
|
||||
let emptyDictionary = Dictionary<String, Float>()
|
||||
</code></pre>
|
||||
<p>如果类型信息可以被推断出来,你可以用<code>[]</code>和<code>[:]</code>来创建空数组和空字典——就像你声明变量或者给函数传参数的时候一样。</p>
|
||||
<pre><code class="lang-swift"> shoppingList = [] // 去逛街并买点东西
|
||||
<pre><code class="lang-swift">shoppingList = [] // 去逛街并买点东西
|
||||
</code></pre>
|
||||
<p><a name="control_flow"></a></p>
|
||||
<h2 id="-">控制流</h2>
|
||||
<p>使用<code>if</code>和<code>switch</code>来进行条件操作,使用<code>for-in</code>、<code>for</code>、<code>while</code>和<code>do-while</code>来进行循环。包裹条件和循环变量括号可以省略,但是语句体的大括号是必须的。</p>
|
||||
<pre><code class="lang-swift"> let individualScores = [75, 43, 103, 87, 12]
|
||||
var teamScore = 0
|
||||
for score in individualScores {
|
||||
if score > 50 {
|
||||
teamScore += 3
|
||||
} else {
|
||||
teamScore += 1
|
||||
}
|
||||
<pre><code class="lang-swift">let individualScores = [75, 43, 103, 87, 12]
|
||||
var teamScore = 0
|
||||
for score in individualScores {
|
||||
if score > 50 {
|
||||
teamScore += 3
|
||||
} else {
|
||||
teamScore += 1
|
||||
}
|
||||
teamScore
|
||||
}
|
||||
teamScore
|
||||
</code></pre>
|
||||
<p>在<code>if</code>语句中,条件必须是一个布尔表达式——这意味着像<code>if score { ... }</code>这样的代码将报错,而不会隐形地与 0 做对比。</p>
|
||||
<p>你可以一起使用<code>if</code>和<code>let</code>来处理值缺失的情况。有些变量的值是可选的。一个可选的值可能是一个具体的值或者是<code>nil</code>,表示值缺失。在类型后面加一个问号来标记这个变量的值是可选的。</p>
|
||||
<pre><code class="lang-swift"> var optionalString: String? = "Hello"
|
||||
optionalString == nil
|
||||
<pre><code class="lang-swift">var optionalString: String? = "Hello"
|
||||
optionalString == nil
|
||||
|
||||
var optionalName: String? = "John Appleseed"
|
||||
var greeting = "Hello!"
|
||||
if let name = optionalName {
|
||||
greeting = "Hello, \(name)"
|
||||
}
|
||||
var optionalName: String? = "John Appleseed"
|
||||
var greeting = "Hello!"
|
||||
if let name = optionalName {
|
||||
greeting = "Hello, \(name)"
|
||||
}
|
||||
</code></pre>
|
||||
<blockquote>
|
||||
<p>练习:</p>
|
||||
<p>把<code>optionalName</code>改成<code>nil</code>,greeting会是什么?添加一个<code>else</code>语句,当<code>optionalName</code>是<code>nil</code>时给greeting赋一个不同的值。</p>
|
||||
<p>练习:<br>把<code>optionalName</code>改成<code>nil</code>,greeting会是什么?添加一个<code>else</code>语句,当<code>optionalName</code>是<code>nil</code>时给greeting赋一个不同的值。</p>
|
||||
</blockquote>
|
||||
<p>如果变量的可选值是<code>nil</code>,条件会判断为<code>false</code>,大括号中的代码会被跳过。如果不是<code>nil</code>,会将值赋给<code>let</code>后面的常量,这样代码块中就可以使用这个值了。</p>
|
||||
<p><code>switch</code>支持任意类型的数据以及各种比较操作——不仅仅是整数以及测试相等。</p>
|
||||
<pre><code class="lang-swift"> let vegetable = "red pepper"
|
||||
switch vegetable {
|
||||
case "celery":
|
||||
let vegetableComment = "Add some raisins and make ants on a log."
|
||||
case "cucumber", "watercress":
|
||||
let vegetableComment = "That would make a good tea sandwich."
|
||||
case let x where x.hasSuffix("pepper"):
|
||||
let vegetableComment = "Is it a spicy \(x)?"
|
||||
default:
|
||||
let vegetableComment = "Everything tastes good in soup."
|
||||
}
|
||||
<pre><code class="lang-swift">let vegetable = "red pepper"
|
||||
switch vegetable {
|
||||
case "celery":
|
||||
let vegetableComment = "Add some raisins and make ants on a log."
|
||||
case "cucumber", "watercress":
|
||||
let vegetableComment = "That would make a good tea sandwich."
|
||||
case let x where x.hasSuffix("pepper"):
|
||||
let vegetableComment = "Is it a spicy \(x)?"
|
||||
default:
|
||||
let vegetableComment = "Everything tastes good in soup."
|
||||
}
|
||||
</code></pre>
|
||||
<blockquote>
|
||||
<p>练习:</p>
|
||||
<p>删除<code>default</code>语句,看看会有什么错误?</p>
|
||||
<p>练习:<br>删除<code>default</code>语句,看看会有什么错误?</p>
|
||||
</blockquote>
|
||||
<p>运行<code>switch</code>中匹配到的子句之后,程序会退出<code>switch</code>语句,并不会继续向下运行,所以不需要在每个子句结尾写<code>break</code>。</p>
|
||||
<p>你可以使用<code>for-in</code>来遍历字典,需要两个变量来表示每个键值对。</p>
|
||||
<pre><code class="lang-swift"> let interestingNumbers = [
|
||||
"Prime": [2, 3, 5, 7, 11, 13],
|
||||
"Fibonacci": [1, 1, 2, 3, 5, 8],
|
||||
"Square": [1, 4, 9, 16, 25],
|
||||
]
|
||||
var largest = 0
|
||||
for (kind, numbers) in interestingNumbers {
|
||||
for number in numbers {
|
||||
if number > largest {
|
||||
largest = number
|
||||
}
|
||||
<pre><code class="lang-swift">let interestingNumbers = [
|
||||
"Prime": [2, 3, 5, 7, 11, 13],
|
||||
"Fibonacci": [1, 1, 2, 3, 5, 8],
|
||||
"Square": [1, 4, 9, 16, 25],
|
||||
]
|
||||
var largest = 0
|
||||
for (kind, numbers) in interestingNumbers {
|
||||
for number in numbers {
|
||||
if number > largest {
|
||||
largest = number
|
||||
}
|
||||
}
|
||||
largest
|
||||
}
|
||||
largest
|
||||
</code></pre>
|
||||
<blockquote>
|
||||
<p>练习:</p>
|
||||
<p>添加另一个变量来记录哪种类型的数字是最大的。</p>
|
||||
<p>练习:<br>添加另一个变量来记录哪种类型的数字是最大的。</p>
|
||||
</blockquote>
|
||||
<p>使用<code>while</code>来重复运行一段代码直到不满足条件。循环条件可以在开头也可以在结尾。</p>
|
||||
<pre><code class="lang-swift"> var n = 2
|
||||
while n < 100 {
|
||||
n = n * 2
|
||||
}
|
||||
n
|
||||
<pre><code class="lang-swift">var n = 2
|
||||
while n < 100 {
|
||||
n = n * 2
|
||||
}
|
||||
n
|
||||
|
||||
var m = 2
|
||||
do {
|
||||
m = m * 2
|
||||
} while m < 100
|
||||
m
|
||||
var m = 2
|
||||
do {
|
||||
m = m * 2
|
||||
} while m < 100
|
||||
m
|
||||
</code></pre>
|
||||
<p>你可以在循环中使用<code>..</code>来表示范围,也可以使用传统的写法,两者是等价的:</p>
|
||||
<pre><code class="lang-swift"> var firstForLoop = 0
|
||||
for i in 0..3 {
|
||||
firstForLoop += i
|
||||
}
|
||||
firstForLoop
|
||||
<pre><code class="lang-swift">var firstForLoop = 0
|
||||
for i in 0..3 {
|
||||
firstForLoop += i
|
||||
}
|
||||
firstForLoop
|
||||
|
||||
var secondForLoop = 0
|
||||
for var i = 0; i < 3; ++i {
|
||||
secondForLoop += 1
|
||||
}
|
||||
secondForLoop
|
||||
var secondForLoop = 0
|
||||
for var i = 0; i < 3; ++i {
|
||||
secondForLoop += 1
|
||||
}
|
||||
secondForLoop
|
||||
</code></pre>
|
||||
<p>使用<code>..</code>创建的范围不包含上界,如果想包含的话需要使用<code>...</code>。</p>
|
||||
<p><a name="functions_and_closures"></a></p>
|
||||
<h2 id="-">函数和闭包</h2>
|
||||
<p>使用<code>func</code>来声明一个函数,使用名字和参数来调用函数。使用<code>-></code>来指定函数返回值。</p>
|
||||
<pre><code class="lang-swift"> func greet(name: String, day: String) -> String {
|
||||
return "Hello \(name), today is \(day)."
|
||||
}
|
||||
greet("Bob", "Tuesday")
|
||||
<pre><code class="lang-swift">func greet(name: String, day: String) -> String {
|
||||
return "Hello \(name), today is \(day)."
|
||||
}
|
||||
greet("Bob", "Tuesday")
|
||||
</code></pre>
|
||||
<blockquote>
|
||||
<p>练习:</p>
|
||||
<p>删除<code>day</code>参数,添加一个参数来表示今天吃了什么午饭。</p>
|
||||
<p>练习:<br>删除<code>day</code>参数,添加一个参数来表示今天吃了什么午饭。</p>
|
||||
</blockquote>
|
||||
<p>使用一个元组来返回多个值。</p>
|
||||
<pre><code class="lang-swift"> func getGasPrices() -> (Double, Double, Double) {
|
||||
return (3.59, 3.69, 3.79)
|
||||
}
|
||||
getGasPrices()
|
||||
<pre><code class="lang-swift">func getGasPrices() -> (Double, Double, Double) {
|
||||
return (3.59, 3.69, 3.79)
|
||||
}
|
||||
getGasPrices()
|
||||
</code></pre>
|
||||
<p>函数可以带有可变个数的参数,这些参数在函数内表现为数组的形式:</p>
|
||||
<pre><code class="lang-swift"> func sumOf(numbers: Int...) -> Int {
|
||||
var sum = 0
|
||||
for number in numbers {
|
||||
sum += number
|
||||
}
|
||||
return sum
|
||||
<pre><code class="lang-swift">func sumOf(numbers: Int...) -> Int {
|
||||
var sum = 0
|
||||
for number in numbers {
|
||||
sum += number
|
||||
}
|
||||
sumOf()
|
||||
sumOf(42, 597, 12)
|
||||
return sum
|
||||
}
|
||||
sumOf()
|
||||
sumOf(42, 597, 12)
|
||||
</code></pre>
|
||||
<blockquote>
|
||||
<p>练习:</p>
|
||||
<p>写一个计算参数平均值的函数。</p>
|
||||
<p>练习:<br>写一个计算参数平均值的函数。</p>
|
||||
</blockquote>
|
||||
<p>函数可以嵌套。被嵌套的函数可以访问外侧函数的变量,你可以使用嵌套函数来重构一个太长或者太复杂的函数。</p>
|
||||
<pre><code class="lang-swift"> func returnFifteen() -> Int {
|
||||
var y = 10
|
||||
func add() {
|
||||
y += 5
|
||||
}
|
||||
add()
|
||||
return y
|
||||
<pre><code class="lang-swift">func returnFifteen() -> Int {
|
||||
var y = 10
|
||||
func add() {
|
||||
y += 5
|
||||
}
|
||||
returnFifteen()
|
||||
add()
|
||||
return y
|
||||
}
|
||||
returnFifteen()
|
||||
</code></pre>
|
||||
<p>函数是第一等类型,这意味着函数可以作为另一个函数的返回值。</p>
|
||||
<pre><code class="lang-swift"> func makeIncrementer() -> (Int -> Int) {
|
||||
func addOne(number: Int) -> Int {
|
||||
return 1 + number
|
||||
}
|
||||
return addOne
|
||||
<pre><code class="lang-swift">func makeIncrementer() -> (Int -> Int) {
|
||||
func addOne(number: Int) -> Int {
|
||||
return 1 + number
|
||||
}
|
||||
var increment = makeIncrementer()
|
||||
increment(7)
|
||||
return addOne
|
||||
}
|
||||
var increment = makeIncrementer()
|
||||
increment(7)
|
||||
</code></pre>
|
||||
<p>函数也可以当做参数传入另一个函数。</p>
|
||||
<pre><code class="lang-swift"> func hasAnyMatches(list: Int[], condition: Int -> Bool) -> Bool {
|
||||
for item in list {
|
||||
if condition(item) {
|
||||
return true
|
||||
}
|
||||
<pre><code class="lang-swift">func hasAnyMatches(list: Int[], condition: Int -> Bool) -> Bool {
|
||||
for item in list {
|
||||
if condition(item) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
func lessThanTen(number: Int) -> Bool {
|
||||
return number < 10
|
||||
}
|
||||
var numbers = [20, 19, 7, 12]
|
||||
hasAnyMatches(numbers, lessThanTen)
|
||||
return false
|
||||
}
|
||||
func lessThanTen(number: Int) -> Bool {
|
||||
return number < 10
|
||||
}
|
||||
var numbers = [20, 19, 7, 12]
|
||||
hasAnyMatches(numbers, lessThanTen)
|
||||
</code></pre>
|
||||
<p>函数实际上是一种特殊的闭包,你可以使用<code>{}</code>来创建一个匿名闭包。使用<code>in</code>将参数和返回值类型声明与闭包函数体进行分离。</p>
|
||||
<pre><code class="lang-swift"> numbers.map({
|
||||
(number: Int) -> Int in
|
||||
let result = 3 * number
|
||||
return result
|
||||
})
|
||||
<pre><code class="lang-swift">numbers.map({
|
||||
(number: Int) -> Int in
|
||||
let result = 3 * number
|
||||
return result
|
||||
})
|
||||
</code></pre>
|
||||
<blockquote>
|
||||
<p>练习:</p>
|
||||
<p>重写闭包,对所有奇数返回 0.</p>
|
||||
<p>练习:<br>重写闭包,对所有奇数返回 0.</p>
|
||||
</blockquote>
|
||||
<p>有很多种创建闭包的方法。如果一个闭包的类型已知,比如作为一个回调函数,你可以忽略参数的类型和返回值。单个语句闭包会把它语句的值当做结果返回。</p>
|
||||
<pre><code class="lang-swift"> numbers.map({ number in 3 * number })
|
||||
<pre><code class="lang-swift">numbers.map({ number in 3 * number })
|
||||
</code></pre>
|
||||
<p>你可以通过参数位置而不是参数名字来引用参数——这个方法在非常短的闭包中非常有用。当一个闭包作为最后一个参数传给一个函数的时候,它可以直接跟在括号后面。</p>
|
||||
<pre><code class="lang-swift"> sort([1, 5, 3, 12, 2]) { $0 > $1 }
|
||||
<pre><code class="lang-swift">sort([1, 5, 3, 12, 2]) { $0 > $1 }
|
||||
</code></pre>
|
||||
<p><a name="objects_and_classes"></a></p>
|
||||
<h2 id="-">对象和类</h2>
|
||||
<p>使用<code>class</code>和类名来创建一个类。类中属性的声明和常量、变量声明一样,唯一的区别就是它们的上下文是类。同样,方法和函数声明也一样。</p>
|
||||
<pre><code class="lang-swift"> class Shape {
|
||||
var numberOfSides = 0
|
||||
func simpleDescription() -> String {
|
||||
return "A shape with \(numberOfSides) sides."
|
||||
}
|
||||
<pre><code class="lang-swift">class Shape {
|
||||
var numberOfSides = 0
|
||||
func simpleDescription() -> String {
|
||||
return "A shape with \(numberOfSides) sides."
|
||||
}
|
||||
}
|
||||
</code></pre>
|
||||
<blockquote>
|
||||
<p>练习:</p>
|
||||
<p>使用<code>let</code>添加一个常量属性,再添加一个接收一个参数的方法。</p>
|
||||
<p>练习:<br>使用<code>let</code>添加一个常量属性,再添加一个接收一个参数的方法。</p>
|
||||
</blockquote>
|
||||
<p>要创建一个类的实例,在类名后面加上括号。使用点语法来访问实例的属性和方法。</p>
|
||||
<pre><code class="lang-swift"> var shape = Shape()
|
||||
shape.numberOfSides = 7
|
||||
var shapeDescription = shape.simpleDescription()
|
||||
<pre><code class="lang-swift">var shape = Shape()
|
||||
shape.numberOfSides = 7
|
||||
var shapeDescription = shape.simpleDescription()
|
||||
</code></pre>
|
||||
<p>这个版本的<code>Shape</code>类缺少了一些重要的东西:一个构造函数来初始化类实例。使用<code>init</code>来创建一个构造器。</p>
|
||||
<pre><code class="lang-swift"> class NamedShape {
|
||||
var numberOfSides: Int = 0
|
||||
var name: String
|
||||
<pre><code class="lang-swift">class NamedShape {
|
||||
var numberOfSides: Int = 0
|
||||
var name: String
|
||||
|
||||
init(name: String) {
|
||||
self.name = name
|
||||
}
|
||||
|
||||
func simpleDescription() -> String {
|
||||
return "A shape with \(numberOfSides) sides."
|
||||
}
|
||||
init(name: String) {
|
||||
self.name = name
|
||||
}
|
||||
|
||||
func simpleDescription() -> String {
|
||||
return "A shape with \(numberOfSides) sides."
|
||||
}
|
||||
}
|
||||
</code></pre>
|
||||
<p>注意<code>self</code>被用来区别实例变量。当你创建实例的时候,像传入函数参数一样给类传入构造器的参数。每个属性都需要赋值——无论是通过声明(就像<code>numberOfSides</code>)还是通过构造器(就像<code>name</code>)。</p>
|
||||
<p>如果你需要在删除对象之前进行一些清理工作,使用<code>deinit</code>创建一个析构函数。</p>
|
||||
<p>子类的定义方法是在它们的类名后面加上父类的名字,用冒号分割。创建类的时候并不需要一个标准的根类,所以你可以忽略父类。</p>
|
||||
<p>子类如果要重写父类的方法的话,需要用<code>override</code>标记——如果没有添加<code>override</code>就重写父类方法的话编译器会报错。编译器同样会检测<code>override</code>标记的方法是否确实在父类中。</p>
|
||||
<pre><code class="lang-swift"> class Square: NamedShape {
|
||||
var sideLength: Double
|
||||
<pre><code class="lang-swift">class Square: NamedShape {
|
||||
var sideLength: Double
|
||||
|
||||
init(sideLength: Double, name: String) {
|
||||
self.sideLength = sideLength
|
||||
super.init(name: name)
|
||||
numberOfSides = 4
|
||||
}
|
||||
|
||||
func area() -> Double {
|
||||
return sideLength * sideLength
|
||||
}
|
||||
|
||||
override func simpleDescription() -> String {
|
||||
return "A square with sides of length \(sideLength)."
|
||||
}
|
||||
init(sideLength: Double, name: String) {
|
||||
self.sideLength = sideLength
|
||||
super.init(name: name)
|
||||
numberOfSides = 4
|
||||
}
|
||||
let test = Square(sideLength: 5.2, name: "my test square")
|
||||
test.area()
|
||||
test.simpleDescription()
|
||||
|
||||
func area() -> Double {
|
||||
return sideLength * sideLength
|
||||
}
|
||||
|
||||
override func simpleDescription() -> String {
|
||||
return "A square with sides of length \(sideLength)."
|
||||
}
|
||||
}
|
||||
let test = Square(sideLength: 5.2, name: "my test square")
|
||||
test.area()
|
||||
test.simpleDescription()
|
||||
</code></pre>
|
||||
<blockquote>
|
||||
<p>练习:</p>
|
||||
<p>创建<code>NamedShape</code>的另一个子类<code>Circle</code>,构造器接收两个参数,一个是半径一个是名称,实现<code>area</code>和<code>describe</code>方法。</p>
|
||||
<p>练习:<br>创建<code>NamedShape</code>的另一个子类<code>Circle</code>,构造器接收两个参数,一个是半径一个是名称,实现<code>area</code>和<code>describe</code>方法。</p>
|
||||
</blockquote>
|
||||
<p>属性可以有 getter 和 setter 。</p>
|
||||
<pre><code class="lang-swift"> class EquilateralTriangle: NamedShape {
|
||||
var sideLength: Double = 0.0
|
||||
<pre><code class="lang-swift">class EquilateralTriangle: NamedShape {
|
||||
var sideLength: Double = 0.0
|
||||
|
||||
init(sideLength: Double, name: String) {
|
||||
self.sideLength = sideLength
|
||||
super.init(name: name)
|
||||
numberOfSides = 3
|
||||
}
|
||||
|
||||
var perimeter: Double {
|
||||
get {
|
||||
return 3.0 * sideLength
|
||||
}
|
||||
set {
|
||||
sideLength = newValue / 3.0
|
||||
}
|
||||
}
|
||||
|
||||
override func simpleDescription() -> String {
|
||||
return "An equilateral triagle with sides of length \(sideLength)."
|
||||
}
|
||||
init(sideLength: Double, name: String) {
|
||||
self.sideLength = sideLength
|
||||
super.init(name: name)
|
||||
numberOfSides = 3
|
||||
}
|
||||
var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle")
|
||||
triangle.perimeter
|
||||
triangle.perimeter = 9.9
|
||||
triangle.sideLength
|
||||
|
||||
var perimeter: Double {
|
||||
get {
|
||||
return 3.0 * sideLength
|
||||
}
|
||||
set {
|
||||
sideLength = newValue / 3.0
|
||||
}
|
||||
}
|
||||
|
||||
override func simpleDescription() -> String {
|
||||
return "An equilateral triagle with sides of length \(sideLength)."
|
||||
}
|
||||
}
|
||||
var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle")
|
||||
triangle.perimeter
|
||||
triangle.perimeter = 9.9
|
||||
triangle.sideLength
|
||||
</code></pre>
|
||||
<p>在<code>perimeter</code>的 setter 中,新值的名字是<code>newValue</code>。你可以在<code>set</code>之后显式的设置一个名字。</p>
|
||||
<p>注意<code>EquilateralTriangle</code>类的构造器执行了三步:</p>
|
||||
@ -945,238 +932,233 @@
|
||||
<li>调用父类的构造器</li>
|
||||
<li>改变父类定义的属性值。其他的工作比如调用方法、getters和setters也可以在这个阶段完成。</li>
|
||||
</ol>
|
||||
<p>如果你不需要计算属性但是需要在设置一个新值之前运行一些代码,使用<code>willSet</code>和<code>didSet</code>。</p>
|
||||
<p>如果你不需要计算属性,但是仍然需要在设置一个新值之前或者之后运行代码,使用<code>willSet</code>和<code>didSet</code>。</p>
|
||||
<p>比如,下面的类确保三角形的边长总是和正方形的边长相同。</p>
|
||||
<pre><code class="lang-swift"> class TriangleAndSquare {
|
||||
var triangle: EquilateralTriangle {
|
||||
willSet {
|
||||
square.sideLength = newValue.sideLength
|
||||
}
|
||||
}
|
||||
var square: Square {
|
||||
willSet {
|
||||
triangle.sideLength = newValue.sideLength
|
||||
}
|
||||
}
|
||||
init(size: Double, name: String) {
|
||||
square = Square(sideLength: size, name: name)
|
||||
triangle = EquilateralTriangle(sideLength: size, name: name)
|
||||
}
|
||||
<pre><code class="lang-swift">class TriangleAndSquare {
|
||||
var triangle: EquilateralTriangle {
|
||||
willSet {
|
||||
square.sideLength = newValue.sideLength
|
||||
}
|
||||
var triangleAndSquare = TriangleAndSquare(size: 10, name: "another test shape")
|
||||
triangleAndSquare.square.sideLength
|
||||
triangleAndSquare.triangle.sideLength
|
||||
triangleAndSquare.square = Square(sideLength: 50, name: "larger square")
|
||||
triangleAndSquare.triangle.sideLength
|
||||
}
|
||||
var square: Square {
|
||||
willSet {
|
||||
triangle.sideLength = newValue.sideLength
|
||||
}
|
||||
}
|
||||
init(size: Double, name: String) {
|
||||
square = Square(sideLength: size, name: name)
|
||||
triangle = EquilateralTriangle(sideLength: size, name: name)
|
||||
}
|
||||
}
|
||||
var triangleAndSquare = TriangleAndSquare(size: 10, name: "another test shape")
|
||||
triangleAndSquare.square.sideLength
|
||||
triangleAndSquare.triangle.sideLength
|
||||
triangleAndSquare.square = Square(sideLength: 50, name: "larger square")
|
||||
triangleAndSquare.triangle.sideLength
|
||||
</code></pre>
|
||||
<p>类中的方法和一般的函数有一个重要的区别,函数的参数名只在函数内部使用,但是方法的参数名需要在调用的时候显式说明(除了第一个参数)。默认情况下,方法的参数名和它在方法内部的名字一样,不过你也可以定义第二个名字,这个名字被用在方法内部。</p>
|
||||
<pre><code class="lang-swift"> class Counter {
|
||||
var count: Int = 0
|
||||
func incrementBy(amount: Int, numberOfTimes times: Int) {
|
||||
count += amount * times
|
||||
}
|
||||
<pre><code class="lang-swift">class Counter {
|
||||
var count: Int = 0
|
||||
func incrementBy(amount: Int, numberOfTimes times: Int) {
|
||||
count += amount * times
|
||||
}
|
||||
var counter = Counter()
|
||||
counter.incrementBy(2, numberOfTimes: 7)
|
||||
}
|
||||
var counter = Counter()
|
||||
counter.incrementBy(2, numberOfTimes: 7)
|
||||
</code></pre>
|
||||
<p>处理变量的可选值时,你可以在操作(比如方法、属性和子脚本)之前加<code>?</code>。如果<code>?</code>之前的值是<code>nil</code>,<code>?</code>后面的东西都会被忽略,并且整个表达式返回<code>nil</code>。否则,<code>?</code>之后的东西都会被运行。在这两种情况下,整个表达式的值也是一个可选值。</p>
|
||||
<pre><code class="lang-swift"> let optionalSquare: Square? = Square(sideLength: 2.5, name: "optional square")
|
||||
let sideLength = optionalSquare?.sideLength
|
||||
<pre><code class="lang-swift">let optionalSquare: Square? = Square(sideLength: 2.5, name: "optional square")
|
||||
let sideLength = optionalSquare?.sideLength
|
||||
</code></pre>
|
||||
<p><a name="enumerations_and_structure"></a></p>
|
||||
<h2 id="-">枚举和结构体</h2>
|
||||
<p>使用<code>enum</code>来创建一个枚举。就像类和其他所有命名类型一样,枚举可以包含方法。</p>
|
||||
<pre><code class="lang-swift"> enum Rank: Int {
|
||||
case Ace = 1
|
||||
case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
|
||||
case Jack, Queen, King
|
||||
func simpleDescription() -> String {
|
||||
switch self {
|
||||
case .Ace:
|
||||
return "ace"
|
||||
case .Jack:
|
||||
return "jack"
|
||||
case .Queen:
|
||||
return "queen"
|
||||
case .King:
|
||||
return "king"
|
||||
default:
|
||||
return String(self.toRaw())
|
||||
}
|
||||
<pre><code class="lang-swift">enum Rank: Int {
|
||||
case Ace = 1
|
||||
case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
|
||||
case Jack, Queen, King
|
||||
func simpleDescription() -> String {
|
||||
switch self {
|
||||
case .Ace:
|
||||
return "ace"
|
||||
case .Jack:
|
||||
return "jack"
|
||||
case .Queen:
|
||||
return "queen"
|
||||
case .King:
|
||||
return "king"
|
||||
default:
|
||||
return String(self.toRaw())
|
||||
}
|
||||
}
|
||||
let ace = Rank.Ace
|
||||
let aceRawValue = ace.toRaw()
|
||||
}
|
||||
let ace = Rank.Ace
|
||||
let aceRawValue = ace.toRaw()
|
||||
</code></pre>
|
||||
<blockquote>
|
||||
<p>练习:</p>
|
||||
<p>写一个函数,通过比较它们的原始值来比较两个<code>Rank</code>值。</p>
|
||||
<p>练习:<br>写一个函数,通过比较它们的原始值来比较两个<code>Rank</code>值。</p>
|
||||
</blockquote>
|
||||
<p>在上面的例子中,枚举原始值的类型是<code>Int</code>,所以你只需要设置第一个原始值。剩下的原始值会按照顺序赋值。你也可以使用字符串或者浮点数作为枚举的原始值。</p>
|
||||
<p>使用<code>toRaw</code>和<code>fromRaw</code>函数来在原始值和枚举值之间进行转换。</p>
|
||||
<pre><code class="lang-swift"> if let convertedRank = Rank.fromRaw(3) {
|
||||
let threeDescription = convertedRank.simpleDescription()
|
||||
}
|
||||
<pre><code class="lang-swift">if let convertedRank = Rank.fromRaw(3) {
|
||||
let threeDescription = convertedRank.simpleDescription()
|
||||
}
|
||||
</code></pre>
|
||||
<p>枚举的成员值是实际值,并不是原始值的另一种表达方法。实际上,如果原始值没有意义,你不需要设置。</p>
|
||||
<pre><code class="lang-swift"> enum Suit {
|
||||
case Spades, Hearts, Diamonds, Clubs
|
||||
func simpleDescription() -> String {
|
||||
switch self {
|
||||
case .Spades:
|
||||
return "spades"
|
||||
case .Hearts:
|
||||
return "hearts"
|
||||
case .Diamonds:
|
||||
return "diamonds"
|
||||
case .Clubs:
|
||||
return "clubs"
|
||||
}
|
||||
<pre><code class="lang-swift">enum Suit {
|
||||
case Spades, Hearts, Diamonds, Clubs
|
||||
func simpleDescription() -> String {
|
||||
switch self {
|
||||
case .Spades:
|
||||
return "spades"
|
||||
case .Hearts:
|
||||
return "hearts"
|
||||
case .Diamonds:
|
||||
return "diamonds"
|
||||
case .Clubs:
|
||||
return "clubs"
|
||||
}
|
||||
|
||||
}
|
||||
let hearts = Suit.Hearts
|
||||
let heartsDescription = hearts.simpleDescription()
|
||||
|
||||
}
|
||||
let hearts = Suit.Hearts
|
||||
let heartsDescription = hearts.simpleDescription()
|
||||
</code></pre>
|
||||
<blockquote>
|
||||
<p>练习:</p>
|
||||
<p>给<code>Suit</code>添加一个<code>color</code>方法,对<code>spades</code>和<code>clubs</code>返回“black”,对<code>hearts</code>和<code>diamonds</code>返回“red”。</p>
|
||||
<p>练习:<br>给<code>Suit</code>添加一个<code>color</code>方法,对<code>spades</code>和<code>clubs</code>返回“black”,对<code>hearts</code>和<code>diamonds</code>返回“red”。</p>
|
||||
</blockquote>
|
||||
<p>注意,有两种方式可以引用<code>Hearts</code>成员:给<code>hearts</code>常量赋值时,枚举成员<code>Suit.Hearts</code>需要用全名来引用,因为常量没有显式指定类型。在<code>switch</code>里,枚举成员使用缩写<code>.Hearts</code>来引用,因为<code>self</code>的值已经知道是一个<code>suit</code>。已知变量类型的情况下你可以使用缩写。</p>
|
||||
<p>使用<code>struct</code>来创建一个结构体。结构体和类有很多相同的地方,比如方法和构造器。它们之间最大的一个区别就是
|
||||
结构体是传值,类是传引用。</p>
|
||||
<pre><code class="lang-swift"> struct Card {
|
||||
var rank: Rank
|
||||
var suit: Suit
|
||||
func simpleDescription() -> String {
|
||||
return "The \(rank.simpleDescription()) of \
|
||||
(suit.simpleDescription())"
|
||||
}
|
||||
<pre><code class="lang-swift">struct Card {
|
||||
var rank: Rank
|
||||
var suit: Suit
|
||||
func simpleDescription() -> String {
|
||||
return "The \(rank.simpleDescription()) of \
|
||||
(suit.simpleDescription())"
|
||||
}
|
||||
let threeOfSpades = Card(rank: .Three, suit: .Spades)
|
||||
let threeOfSpadesDescription = threeOfSpades.simpleDescription()
|
||||
}
|
||||
let threeOfSpades = Card(rank: .Three, suit: .Spades)
|
||||
let threeOfSpadesDescription = threeOfSpades.simpleDescription()
|
||||
</code></pre>
|
||||
<blockquote>
|
||||
<p>练习:</p>
|
||||
<p>给<code>Card</code>添加一个方法,创建一副完整的扑克牌并把每张牌的 rank 和 suit 对应起来。</p>
|
||||
<p>练习:<br>给<code>Card</code>添加一个方法,创建一副完整的扑克牌并把每张牌的 rank 和 suit 对应起来。</p>
|
||||
</blockquote>
|
||||
<p>一个枚举成员的实例可以有实例值。相同枚举成员的实例可以有不同的值。创建实例的时候传入值即可。实例值和原始值是不同的:枚举成员的原始值对于所有实例都是相同的,而且你是在定义枚举的时候设置原始值。</p>
|
||||
<p>例如,考虑从服务器获取日出和日落的时间。服务器会返回正常结果或者错误信息。</p>
|
||||
<pre><code class="lang-swift"> enum ServerResponse {
|
||||
case Result(String, String)
|
||||
case Error(String)
|
||||
}
|
||||
<pre><code class="lang-swift">enum ServerResponse {
|
||||
case Result(String, String)
|
||||
case Error(String)
|
||||
}
|
||||
|
||||
let success = ServerResponse.Result("6:00 am", "8:09 pm")
|
||||
let failure = ServerResponse.Error("Out of cheese.")
|
||||
let success = ServerResponse.Result("6:00 am", "8:09 pm")
|
||||
let failure = ServerResponse.Error("Out of cheese.")
|
||||
|
||||
switch success {
|
||||
case let .Result(sunrise, sunset):
|
||||
let serverResponse = "Sunrise is at \(sunrise) and sunset is at \(sunset)."
|
||||
case let .Error(error):
|
||||
let serverResponse = "Failure... \(error)"
|
||||
}
|
||||
switch success {
|
||||
case let .Result(sunrise, sunset):
|
||||
let serverResponse = "Sunrise is at \(sunrise) and sunset is at \(sunset)."
|
||||
case let .Error(error):
|
||||
let serverResponse = "Failure... \(error)"
|
||||
}
|
||||
</code></pre>
|
||||
<blockquote>
|
||||
<p>练习:</p>
|
||||
<p>给<code>ServerResponse</code>和<code>switch</code>添加第三种情况。</p>
|
||||
<p>练习:<br>给<code>ServerResponse</code>和<code>switch</code>添加第三种情况。</p>
|
||||
</blockquote>
|
||||
<p>注意如何从<code>ServerResponse</code>中提取日升和日落时间。</p>
|
||||
<p><a name="protocols_and_extensions"></a></p>
|
||||
<h2 id="-">接口和扩展</h2>
|
||||
<p>使用<code>protocol</code>来声明一个接口。</p>
|
||||
<pre><code class="lang-swift"> protocol ExampleProtocol {
|
||||
var simpleDescription: String { get }
|
||||
mutating func adjust()
|
||||
}
|
||||
<h2 id="-">协议和扩展</h2>
|
||||
<p>使用<code>protocol</code>来声明一个协议。</p>
|
||||
<pre><code class="lang-swift">protocol ExampleProtocol {
|
||||
var simpleDescription: String { get }
|
||||
mutating func adjust()
|
||||
}
|
||||
</code></pre>
|
||||
<p>类、枚举和结构体都可以实现接口。</p>
|
||||
<pre><code class="lang-swift"> class SimpleClass: ExampleProtocol {
|
||||
var simpleDescription: String = "A very simple class."
|
||||
var anotherProperty: Int = 69105
|
||||
func adjust() {
|
||||
simpleDescription += " Now 100% adjusted."
|
||||
}
|
||||
<p>类、枚举和结构体都可以实现协议。</p>
|
||||
<pre><code class="lang-swift">class SimpleClass: ExampleProtocol {
|
||||
var simpleDescription: String = "A very simple class."
|
||||
var anotherProperty: Int = 69105
|
||||
func adjust() {
|
||||
simpleDescription += " Now 100% adjusted."
|
||||
}
|
||||
var a = SimpleClass()
|
||||
a.adjust()
|
||||
let aDescription = a.simpleDescription
|
||||
}
|
||||
var a = SimpleClass()
|
||||
a.adjust()
|
||||
let aDescription = a.simpleDescription
|
||||
|
||||
struct SimpleStructure: ExampleProtocol {
|
||||
var simpleDescription: String = "A simple structure"
|
||||
mutating func adjust() {
|
||||
simpleDescription += " (adjusted)"
|
||||
}
|
||||
struct SimpleStructure: ExampleProtocol {
|
||||
var simpleDescription: String = "A simple structure"
|
||||
mutating func adjust() {
|
||||
simpleDescription += " (adjusted)"
|
||||
}
|
||||
var b = SimpleStructure()
|
||||
b.adjust()
|
||||
let bDescription = b.simpleDescription
|
||||
}
|
||||
var b = SimpleStructure()
|
||||
b.adjust()
|
||||
let bDescription = b.simpleDescription
|
||||
</code></pre>
|
||||
<blockquote>
|
||||
<p>练习:</p>
|
||||
<p>写一个实现这个接口的枚举。</p>
|
||||
<p>写一个实现这个协议的枚举。</p>
|
||||
</blockquote>
|
||||
<p>注意声明<code>SimpleStructure</code>时候<code>mutating</code>关键字用来标记一个会修改结构体的方法。<code>SimpleClass</code>的声明不需要标记任何方法因为类中的方法经常会修改类。</p>
|
||||
<p>使用<code>extension</code>来为现有的类型添加功能,比如添加一个计算属性的方法。你可以使用扩展来给任意类型添加协议,甚至是你从外部库或者框架中导入的类型。</p>
|
||||
<pre><code class="lang-swift"> extension Int: ExampleProtocol {
|
||||
var simpleDescription: String {
|
||||
return "The number \(self)"
|
||||
}
|
||||
mutating func adjust() {
|
||||
self += 42
|
||||
}
|
||||
<p>使用<code>extension</code>来为现有的类型添加功能,比如新的方法和参数。你可以使用扩展来改造定义在别处,甚至是从外部库或者框架引入的一个类型,使得这个类型遵循某个协议。</p>
|
||||
<pre><code class="lang-swift">extension Int: ExampleProtocol {
|
||||
var simpleDescription: String {
|
||||
return "The number \(self)"
|
||||
}
|
||||
7.simpleDescription
|
||||
mutating func adjust() {
|
||||
self += 42
|
||||
}
|
||||
}
|
||||
7.simpleDescription
|
||||
</code></pre>
|
||||
<blockquote>
|
||||
<p>练习:</p>
|
||||
<p>给<code>Double</code>类型写一个扩展,添加<code>absoluteValue</code>功能。</p>
|
||||
</blockquote>
|
||||
<p>你可以像使用其他命名类型一样使用接口名——例如,创建一个有不同类型但是都实现一个接口的对象集合。当你处理类型是接口的值时,接口外定义的方法不可用。</p>
|
||||
<pre><code class="lang-swift"> let protocolValue: ExampleProtocol = a
|
||||
protocolValue.simpleDescription
|
||||
// protocolValue.anotherProperty // Uncomment to see the error
|
||||
<p>你可以像使用其他命名类型一样使用协议名——例如,创建一个有不同类型但是都实现一个协议的对象集合。当你处理类型是协议的值时,协议外定义的方法不可用。</p>
|
||||
<pre><code class="lang-swift">let protocolValue: ExampleProtocol = a
|
||||
protocolValue.simpleDescription
|
||||
// protocolValue.anotherProperty // Uncomment to see the error
|
||||
</code></pre>
|
||||
<p>即使<code>protocolValue</code>变量运行时的类型是<code>simpleClass</code>,编译器会把它的类型当做<code>ExampleProtocol</code>。这表示你不能调用类在它实现的接口之外实现的方法或者属性。</p>
|
||||
<p>即使<code>protocolValue</code>变量运行时的类型是<code>simpleClass</code>,编译器会把它的类型当做<code>ExampleProtocol</code>。这表示你不能调用类在它实现的协议之外实现的方法或者属性。</p>
|
||||
<p><a name="generics"></a></p>
|
||||
<h2 id="-">泛型</h2>
|
||||
<p>在尖括号里写一个名字来创建一个泛型函数或者类型。</p>
|
||||
<pre><code class="lang-swift"> func repeat<ItemType>(item: ItemType, times: Int) -> ItemType[] {
|
||||
var result = ItemType[]()
|
||||
for i in 0..times {
|
||||
result += item
|
||||
}
|
||||
return result
|
||||
<pre><code class="lang-swift">func repeat<ItemType>(item: ItemType, times: Int) -> ItemType[] {
|
||||
var result = ItemType[]()
|
||||
for i in 0..times {
|
||||
result += item
|
||||
}
|
||||
repeat("knock", 4)
|
||||
return result
|
||||
}
|
||||
repeat("knock", 4)
|
||||
</code></pre>
|
||||
<p>你也可以创建泛型类、枚举和结构体。</p>
|
||||
<pre><code class="lang-swift"> // Reimplement the Swift standard library's optional type
|
||||
enum OptionalValue<T> {
|
||||
case None
|
||||
case Some(T)
|
||||
}
|
||||
var possibleInteger: OptionalValue<Int> = .None
|
||||
possibleInteger = .Some(100)
|
||||
<pre><code class="lang-swift">// Reimplement the Swift standard library's optional type
|
||||
enum OptionalValue<T> {
|
||||
case None
|
||||
case Some(T)
|
||||
}
|
||||
var possibleInteger: OptionalValue<Int> = .None
|
||||
possibleInteger = .Some(100)
|
||||
</code></pre>
|
||||
<p>在类型名后面使用<code>where</code>来指定一个需求列表——例如,要限定实现一个协议的类型,需要限定两个类型要相同,或者限定一个类必须有一个特定的父类。</p>
|
||||
<pre><code class="lang-swift"> func anyCommonElements <T, U where T: Sequence, U: Sequence, T.GeneratorType.Element: Equatable, T.GeneratorType.Element == U.GeneratorType.Element> (lhs: T, rhs: U) -> Bool {
|
||||
for lhsItem in lhs {
|
||||
for rhsItem in rhs {
|
||||
if lhsItem == rhsItem {
|
||||
return true
|
||||
}
|
||||
<p>在类型名后面使用<code>where</code>来指定对类型的需求,比如,限定类型实现某一个协议,限定两个类型是相同的,或者限定某个类必须有一个特定的父类</p>
|
||||
<pre><code class="lang-swift">func anyCommonElements <T, U where T: Sequence, U: Sequence, T.GeneratorType.Element: Equatable, T.GeneratorType.Element == U.GeneratorType.Element> (lhs: T, rhs: U) -> Bool {
|
||||
for lhsItem in lhs {
|
||||
for rhsItem in rhs {
|
||||
if lhsItem == rhsItem {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
anyCommonElements([1, 2, 3], [3])
|
||||
return false
|
||||
}
|
||||
anyCommonElements([1, 2, 3], [3])
|
||||
</code></pre>
|
||||
<blockquote>
|
||||
<p>练习:</p>
|
||||
<p>修改<code>anyCommonElements</code>函数来创建一个函数,返回一个数组,内容是两个序列的共有元素。</p>
|
||||
<p>练习:<br>修改<code>anyCommonElements</code>函数来创建一个函数,返回一个数组,内容是两个序列的共有元素。</p>
|
||||
</blockquote>
|
||||
<p>简单起见,你可以忽略<code>where</code>,只在冒号后面写接口或者类名。<code><T: Equatable></code>和<code><T where T: Equatable></code>是等价的。</p>
|
||||
<p>简单起见,你可以忽略<code>where</code>,只在冒号后面写协议或者类名。<code><T: Equatable></code>和<code><T where T: Equatable></code>是等价的。</p>
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
8
chapter1/chapter1.html
Executable file → Normal file
8
chapter1/chapter1.html
Executable file → Normal file
@ -46,7 +46,7 @@
|
||||
|
||||
|
||||
|
||||
<div class="book" data-level="1" data-basepath=".." data-revision="1402677669306">
|
||||
<div class="book" data-level="1" data-basepath=".." data-revision="1402750255397">
|
||||
<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>
|
||||
@ -268,7 +268,7 @@
|
||||
<li class="chapter " data-level="2.12" data-path="chapter2/12_Subscripts.html">
|
||||
|
||||
<a href="../chapter2/12_Subscripts.html">
|
||||
<i class="fa fa-check"></i> <b>2.12.</b> 附属脚本
|
||||
<i class="fa fa-check"></i> <b>2.12.</b> 下标脚本
|
||||
</a>
|
||||
|
||||
|
||||
@ -520,7 +520,7 @@
|
||||
|
||||
<a href="../chapter2/11_Methods.html" title="方法" class="chapter " data-progress="2.11" style="left: 18.42105263157895%;"></a>
|
||||
|
||||
<a href="../chapter2/12_Subscripts.html" title="附属脚本" class="chapter " data-progress="2.12" style="left: 21.05263157894737%;"></a>
|
||||
<a href="../chapter2/12_Subscripts.html" title="下标脚本" class="chapter " data-progress="2.12" style="left: 21.05263157894737%;"></a>
|
||||
|
||||
<a href="../chapter2/13_Inheritance.html" title="继承" class="chapter " data-progress="2.13" style="left: 23.68421052631579%;"></a>
|
||||
|
||||
@ -587,7 +587,7 @@
|
||||
|
||||
<div class="page-inner">
|
||||
|
||||
<section class="normal" id="section-gitbook_87">
|
||||
<section class="normal" id="section-gitbook_34">
|
||||
|
||||
<h1 id="-swift">欢迎使用 Swift</h1>
|
||||
<p>在本章中您将了解 Swift 的特性和开发历史,并对 Swift 有一个初步的了解。</p>
|
||||
|
||||
Reference in New Issue
Block a user