ffix conflict
This commit is contained in:
@ -46,7 +46,7 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
<div class="book" data-level="1.1" data-basepath=".." data-revision="1402451678088">
|
<div class="book" data-level="1.1" data-basepath=".." data-revision="1402469309776">
|
||||||
<div class="book-header">
|
<div class="book-header">
|
||||||
<!-- Actions Left -->
|
<!-- Actions Left -->
|
||||||
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
||||||
@ -587,7 +587,7 @@
|
|||||||
|
|
||||||
<div class="page-inner">
|
<div class="page-inner">
|
||||||
|
|
||||||
<section class="normal" id="section-gitbook_105">
|
<section class="normal" id="section-gitbook_5">
|
||||||
|
|
||||||
<h1 id="-swift">关于 Swift</h1>
|
<h1 id="-swift">关于 Swift</h1>
|
||||||
<hr>
|
<hr>
|
||||||
|
|||||||
@ -46,7 +46,7 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
<div class="book" data-level="1.2" data-basepath=".." data-revision="1402451678088">
|
<div class="book" data-level="1.2" data-basepath=".." data-revision="1402469309776">
|
||||||
<div class="book-header">
|
<div class="book-header">
|
||||||
<!-- Actions Left -->
|
<!-- Actions Left -->
|
||||||
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
||||||
@ -587,7 +587,7 @@
|
|||||||
|
|
||||||
<div class="page-inner">
|
<div class="page-inner">
|
||||||
|
|
||||||
<section class="normal" id="section-gitbook_107">
|
<section class="normal" id="section-gitbook_7">
|
||||||
|
|
||||||
<h1 id="swift-">Swift 初见</h1>
|
<h1 id="swift-">Swift 初见</h1>
|
||||||
<hr>
|
<hr>
|
||||||
|
|||||||
@ -46,7 +46,7 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
<div class="book" data-level="1" data-basepath=".." data-revision="1402451678088">
|
<div class="book" data-level="1" data-basepath=".." data-revision="1402469309776">
|
||||||
<div class="book-header">
|
<div class="book-header">
|
||||||
<!-- Actions Left -->
|
<!-- Actions Left -->
|
||||||
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
||||||
@ -587,7 +587,7 @@
|
|||||||
|
|
||||||
<div class="page-inner">
|
<div class="page-inner">
|
||||||
|
|
||||||
<section class="normal" id="section-gitbook_109">
|
<section class="normal" id="section-gitbook_9">
|
||||||
|
|
||||||
<h1 id="-swift">欢迎使用 Swift</h1>
|
<h1 id="-swift">欢迎使用 Swift</h1>
|
||||||
<p>在本章中您将了解 Swift 的特性和开发历史,并对 Swift 有一个初步的了解。</p>
|
<p>在本章中您将了解 Swift 的特性和开发历史,并对 Swift 有一个初步的了解。</p>
|
||||||
|
|||||||
@ -46,7 +46,7 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
<div class="book" data-level="2.1" data-basepath=".." data-revision="1402451678088">
|
<div class="book" data-level="2.1" data-basepath=".." data-revision="1402469309776">
|
||||||
<div class="book-header">
|
<div class="book-header">
|
||||||
<!-- Actions Left -->
|
<!-- Actions Left -->
|
||||||
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
||||||
@ -587,7 +587,7 @@
|
|||||||
|
|
||||||
<div class="page-inner">
|
<div class="page-inner">
|
||||||
|
|
||||||
<section class="normal" id="section-gitbook_112">
|
<section class="normal" id="section-gitbook_12">
|
||||||
|
|
||||||
<h1 id="-">基础部分</h1>
|
<h1 id="-">基础部分</h1>
|
||||||
<hr>
|
<hr>
|
||||||
|
|||||||
@ -46,7 +46,7 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
<div class="book" data-level="2.2" data-basepath=".." data-revision="1402451678088">
|
<div class="book" data-level="2.2" data-basepath=".." data-revision="1402469309776">
|
||||||
<div class="book-header">
|
<div class="book-header">
|
||||||
<!-- Actions Left -->
|
<!-- Actions Left -->
|
||||||
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
||||||
@ -587,7 +587,7 @@
|
|||||||
|
|
||||||
<div class="page-inner">
|
<div class="page-inner">
|
||||||
|
|
||||||
<section class="normal" id="section-gitbook_147">
|
<section class="normal" id="section-gitbook_47">
|
||||||
|
|
||||||
<h1 id="-">基本运算符</h1>
|
<h1 id="-">基本运算符</h1>
|
||||||
<hr>
|
<hr>
|
||||||
|
|||||||
@ -46,7 +46,7 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
<div class="book" data-level="2.3" data-basepath=".." data-revision="1402451678088">
|
<div class="book" data-level="2.3" data-basepath=".." data-revision="1402469309776">
|
||||||
<div class="book-header">
|
<div class="book-header">
|
||||||
<!-- Actions Left -->
|
<!-- Actions Left -->
|
||||||
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
||||||
@ -587,7 +587,7 @@
|
|||||||
|
|
||||||
<div class="page-inner">
|
<div class="page-inner">
|
||||||
|
|
||||||
<section class="normal" id="section-gitbook_114">
|
<section class="normal" id="section-gitbook_14">
|
||||||
|
|
||||||
<h1 id="-strings-and-characters-">字符串和字符 (Strings and Characters)</h1>
|
<h1 id="-strings-and-characters-">字符串和字符 (Strings and Characters)</h1>
|
||||||
<hr>
|
<hr>
|
||||||
|
|||||||
@ -46,7 +46,7 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
<div class="book" data-level="2.4" data-basepath=".." data-revision="1402451678088">
|
<div class="book" data-level="2.4" data-basepath=".." data-revision="1402469309776">
|
||||||
<div class="book-header">
|
<div class="book-header">
|
||||||
<!-- Actions Left -->
|
<!-- Actions Left -->
|
||||||
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
||||||
@ -587,7 +587,7 @@
|
|||||||
|
|
||||||
<div class="page-inner">
|
<div class="page-inner">
|
||||||
|
|
||||||
<section class="normal" id="section-gitbook_126">
|
<section class="normal" id="section-gitbook_26">
|
||||||
|
|
||||||
<h1 id="-collection-types-">集合类型 (Collection Types)</h1>
|
<h1 id="-collection-types-">集合类型 (Collection Types)</h1>
|
||||||
<hr>
|
<hr>
|
||||||
|
|||||||
@ -46,7 +46,7 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
<div class="book" data-level="2.5" data-basepath=".." data-revision="1402451678088">
|
<div class="book" data-level="2.5" data-basepath=".." data-revision="1402469309776">
|
||||||
<div class="book-header">
|
<div class="book-header">
|
||||||
<!-- Actions Left -->
|
<!-- Actions Left -->
|
||||||
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
||||||
@ -587,7 +587,7 @@
|
|||||||
|
|
||||||
<div class="page-inner">
|
<div class="page-inner">
|
||||||
|
|
||||||
<section class="normal" id="section-gitbook_128">
|
<section class="normal" id="section-gitbook_28">
|
||||||
|
|
||||||
<h1 id="-">控制流</h1>
|
<h1 id="-">控制流</h1>
|
||||||
<hr>
|
<hr>
|
||||||
|
|||||||
@ -46,7 +46,7 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
<div class="book" data-level="2.6" data-basepath=".." data-revision="1402451678088">
|
<div class="book" data-level="2.6" data-basepath=".." data-revision="1402469309776">
|
||||||
<div class="book-header">
|
<div class="book-header">
|
||||||
<!-- Actions Left -->
|
<!-- Actions Left -->
|
||||||
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
||||||
@ -587,7 +587,7 @@
|
|||||||
|
|
||||||
<div class="page-inner">
|
<div class="page-inner">
|
||||||
|
|
||||||
<section class="normal" id="section-gitbook_130">
|
<section class="normal" id="section-gitbook_30">
|
||||||
|
|
||||||
<h1 id="-functions-">函数(Functions)</h1>
|
<h1 id="-functions-">函数(Functions)</h1>
|
||||||
<hr>
|
<hr>
|
||||||
|
|||||||
@ -46,7 +46,7 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
<div class="book" data-level="2.7" data-basepath=".." data-revision="1402451678088">
|
<div class="book" data-level="2.7" data-basepath=".." data-revision="1402469309776">
|
||||||
<div class="book-header">
|
<div class="book-header">
|
||||||
<!-- Actions Left -->
|
<!-- Actions Left -->
|
||||||
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
||||||
@ -587,7 +587,7 @@
|
|||||||
|
|
||||||
<div class="page-inner">
|
<div class="page-inner">
|
||||||
|
|
||||||
<section class="normal" id="section-gitbook_132">
|
<section class="normal" id="section-gitbook_32">
|
||||||
|
|
||||||
<h1 id="-">闭包</h1>
|
<h1 id="-">闭包</h1>
|
||||||
<hr>
|
<hr>
|
||||||
|
|||||||
@ -46,7 +46,7 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
<div class="book" data-level="2.8" data-basepath=".." data-revision="1402451678088">
|
<div class="book" data-level="2.8" data-basepath=".." data-revision="1402469309776">
|
||||||
<div class="book-header">
|
<div class="book-header">
|
||||||
<!-- Actions Left -->
|
<!-- Actions Left -->
|
||||||
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
||||||
@ -587,7 +587,7 @@
|
|||||||
|
|
||||||
<div class="page-inner">
|
<div class="page-inner">
|
||||||
|
|
||||||
<section class="normal" id="section-gitbook_139">
|
<section class="normal" id="section-gitbook_38">
|
||||||
|
|
||||||
<h1 id="-enumerations-">枚举(Enumerations)</h1>
|
<h1 id="-enumerations-">枚举(Enumerations)</h1>
|
||||||
<hr>
|
<hr>
|
||||||
|
|||||||
@ -46,7 +46,7 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
<div class="book" data-level="2.9" data-basepath=".." data-revision="1402451678088">
|
<div class="book" data-level="2.9" data-basepath=".." data-revision="1402469309776">
|
||||||
<div class="book-header">
|
<div class="book-header">
|
||||||
<!-- Actions Left -->
|
<!-- Actions Left -->
|
||||||
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
||||||
@ -587,7 +587,7 @@
|
|||||||
|
|
||||||
<div class="page-inner">
|
<div class="page-inner">
|
||||||
|
|
||||||
<section class="normal" id="section-gitbook_138">
|
<section class="normal" id="section-gitbook_40">
|
||||||
|
|
||||||
<h3 id="-">类和结构体</h3>
|
<h3 id="-">类和结构体</h3>
|
||||||
<p>本页包含内容:</p>
|
<p>本页包含内容:</p>
|
||||||
@ -598,6 +598,261 @@
|
|||||||
<li>类和结构体的选择</li>
|
<li>类和结构体的选择</li>
|
||||||
<li>集合(collection)类型的赋值与复制行为</li>
|
<li>集合(collection)类型的赋值与复制行为</li>
|
||||||
</ul>
|
</ul>
|
||||||
|
<p>类和结构体是人们构建代码所用的一种通用且灵活的构造体。为了在类和结构体中实现各种功能,我们必须要严格按照对于常量,变量以及函数所规定的语法规则来定义属性和添加方法。</p>
|
||||||
|
<p>与其他编程语言所不同的是,Swift 并不要求你为自定义类和结构去创建独立的接口和实现文件。你所要做的是在一个单一文件中定义一个类或者结构体,系统将会自动生成面向其它代码的外部接口。</p>
|
||||||
|
<blockquote>
|
||||||
|
<p>通常一个<code>类</code>的实例被称为<code>对象</code>。然而在Swift 中,类和结构体的关系要比在其他语言中更加的密切,本章中所讨论的大部分功能都可以用在类和结构体上。因此,我们会主要使用<code>实例</code>而不是<code>对象</code>。</p>
|
||||||
|
</blockquote>
|
||||||
|
<h3 id="-">类和结构体对比</h3>
|
||||||
|
<p>Swift 中类和结构体有很多共同点。共同处在于:</p>
|
||||||
|
<ul>
|
||||||
|
<li>定义属性用于储存值</li>
|
||||||
|
<li>定义方法用于提供功能</li>
|
||||||
|
<li>定义下标用于通过下标语法访问值</li>
|
||||||
|
<li>定义初始化器用于生成初始化值</li>
|
||||||
|
<li>通过扩展以增加默认实现的功能</li>
|
||||||
|
<li>符合协议以对某类提供标准功能</li>
|
||||||
|
</ul>
|
||||||
|
<p>更多信息请参见 <a href="http://" target="_blank">属性</a>,<a href="http://" target="_blank">方法</a>,<a href="http://" target="_blank">下标</a>,<a href="http://" target="_blank">初始化</a>,<a href="http://" target="_blank">扩展</a>,和<a href="http://" target="_blank">协议</a>。</p>
|
||||||
|
<p>与结构体相比,类还有如下的附加功能:</p>
|
||||||
|
<ul>
|
||||||
|
<li>继承允许一个类继承另一个类的特征</li>
|
||||||
|
<li>类型转换允许在运行时检查和解释一个类实例的类型</li>
|
||||||
|
<li>取消初始化器允许一个类实例释放任何其所被分配的资源</li>
|
||||||
|
<li>引用计数允许对一个类的多次引用</li>
|
||||||
|
</ul>
|
||||||
|
<p>更多信息请参见<a href="http://" target="_blank">继承</a>,<a href="http://" target="_blank">类型转换</a>,<a href="http://" target="_blank">初始化</a>,和<a href="http://" target="_blank">自动引用计数</a>。</p>
|
||||||
|
<blockquote>
|
||||||
|
<p>结构体总是通过被复制的方式在代码中传递,因此请不要使用引用计数。</p>
|
||||||
|
</blockquote>
|
||||||
|
<h3 id="-">定义</h3>
|
||||||
|
<p>类和结构体有着类似的定义方式。我们通过关键字<code>class</code>和<code>struct</code>来分别表示类和结构体,并在一对大括号中定义它们的具体内容:</p>
|
||||||
|
<pre><code>class SomeClass {
|
||||||
|
// class definition goes here
|
||||||
|
}
|
||||||
|
struct SomeStructure {
|
||||||
|
// structure definition goes here
|
||||||
|
}
|
||||||
|
</code></pre><blockquote>
|
||||||
|
<p>在你每次定义一个新类或者结构体的时候,实际上你是有效地定义了一个新的Swift 类型。因此请使用 <code>UpperCamelCase</code> 这种方式来命名(如 <code>SomeClass</code> 和<code>SomeStructure</code>等),以便符合标准Swift 类型的大写命名风格(如<code>String</code>,<code>Int</code>和<code>Bool</code>)。相反的,请使用<code>lowerCamelCase</code>这种方式为属性和方法命名(如<code>framerate</code>和<code>incrementCount</code>),以便和类区分。</p>
|
||||||
|
</blockquote>
|
||||||
|
<p>以下是定义结构体和定义类的示例:</p>
|
||||||
|
<pre><code>struct Resolution {
|
||||||
|
var width = 0
|
||||||
|
var heigth = 0
|
||||||
|
}
|
||||||
|
class VideoMode {
|
||||||
|
var resolution = Resolution()
|
||||||
|
var interlaced = false
|
||||||
|
var frameRate = 0.0
|
||||||
|
var name: String?
|
||||||
|
}
|
||||||
|
</code></pre><p>在上面的示例中我们定义了一个名为<code>Resolution</code>的结构体,用来描述一个显示器的像素分辨率。这个结构体包含了两个名为<code>width</code>和<code>height</code>的储存属性。储存属性是捆绑和储存在类或结构体中的常量或变量。当这两个属性被初始化为整数<code>0</code>的时候,它们会被推断为<code>Int</code>类型。</p>
|
||||||
|
<p>在上面的示例中我们还定义了一个名为<code>VideoMode</code>的类,用来描述一个视频显示器的特定模式。这个类包含了四个储存属性变量。第一个是<code>分辨率</code>,它被初始化为一个新的<code>Resolution</code>结构体的实例,具有<code>Resolution</code>的属性类型。新<code>VideoMode</code>实例同时还会初始化其它三个属性,它们分别是,初始值为<code>false</code>(意为“non-interlaced video”)的<code>inteflaced</code>,回放帧率初始值为<code>0.0</code>的<code>frameRate</code>和值为可选<code>String</code>的<code>name</code>。<code>name</code>属性会被自动赋予一个默认值<code>nil</code>,意为“没有<code>name</code>值”,因它是一个可选类型。</p>
|
||||||
|
<h3 id="-">类和结构体实例</h3>
|
||||||
|
<p><code>Resolution</code>结构体和<code>VideoMode</code>类的定义仅描述了什么是<code>Resolution</code>和<code>VideoMode</code>。它们并没有描述一个特定的分辨率(resolution)或者视频模式(video mode)。为了描述一个特定的分辨率或者视频模式,我们需要生成一个它们的实例。</p>
|
||||||
|
<p>生成结构体和类实例的语法非常相似:</p>
|
||||||
|
<pre><code>let someResolution = Resolution()
|
||||||
|
let someVideoMode = VideoMode()
|
||||||
|
</code></pre><p>结构体和类都使用初始化器语法来生成新的实例。初始化器语法的最简单形式是在结构体或者类的类型名称后跟随一个空括弧,如<code>Resolution()</code>或<code>VideoMode()</code>。通过这种方式所创建的类或者结构体实例,其属均会被初始化为默认值。<a href="http://" target="_blank">Initialization</a>章节会对类和结构体的初始化进行更详细的讨论。</p>
|
||||||
|
<h3 id="-">属性访问</h3>
|
||||||
|
<p>通过使用<em>点语法</em>(<em>dot syntax</em>),你可以访问实例中所含有的属性。其语法规则是,实例名后面紧跟属性名,两者通过点号(.)连接:</p>
|
||||||
|
<pre><code>println("The width of someResolution is \(someResolution.width)")
|
||||||
|
// prints "The width of someResolution is 0"
|
||||||
|
</code></pre><p>在上面的例子中,<code>someResolution.width</code>引用<code>someResolution</code>的<code>width</code>属性,返回<code>width</code>的初始值<code>0</code>。</p>
|
||||||
|
<p>你也可以访问子属性,如何<code>VideoMode</code>中<code>Resolution</code>属性的<code>width</code>属性:</p>
|
||||||
|
<pre><code>println("The width of someVideoMode is \(someVideoMode.resolution.width)")
|
||||||
|
// prints "The width of someVideoMode is 0"
|
||||||
|
</code></pre><p>你也可以使用点语法为属性变量赋值:</p>
|
||||||
|
<pre><code>someVideoMode.resolution.width = 12880
|
||||||
|
println("The width of someVideoMode is now \(someVideoMode.resolution.width)")
|
||||||
|
// prints "The width of someVideoMode is now 1280"
|
||||||
|
</code></pre><blockquote>
|
||||||
|
<p>与Objective-C 语言不同的是,Swift 允许直接设置结构体属性的子属性。上面的最后一个例子,就是直接设置了<code>someVideoMode</code>中<code>resolution</code>属性的<code>width</code>这个子属性,以上操作并不需要从新设置<code>resolution</code>属性。</p>
|
||||||
|
</blockquote>
|
||||||
|
<h3 id="-">结构体类型的成员逐一初始化器</h3>
|
||||||
|
<p>//Memberwise Initializers for structure Types</p>
|
||||||
|
<p>所有结构体都有一个自动生成的成员逐一初始化器,用于初始化新结构体实例中成员的属性。新实例中各个属性的初始值可以通过属性的名称传递到成员逐一初始化器之中:</p>
|
||||||
|
<pre><code>let vga = resolution(width:640, heigth: 480)
|
||||||
|
</code></pre><p>与结构体不同,类实例没有默认的成员逐一初始化器。<a href="http://" target="_blank">Initialization</a>章节会对初始化器进行更详细的讨论。</p>
|
||||||
|
<h3 id="-">结构体和枚举是值类型</h3>
|
||||||
|
<p>值类型被赋予给一个变量,常数或者本身被传递给一个函数的时候,实际上操作的是其的拷贝。</p>
|
||||||
|
<p>在之前的章节中,我们已经大量使用了值类型。实际上,在Swift 中,所有的基本类型:整数(Integer)、浮点数(floating-point)、布尔值(Booleans)、字符串(string)、数组(array)和字典(dictionaries),都是值类型,并且都是以结构体的形式在后台所实现。</p>
|
||||||
|
<p>在Swift中,所有的结构体和枚举都是值类型。这意味着它们的实例,以及实例中所包含的任何值类型属性,在代码中传递的时候都会被复制。</p>
|
||||||
|
<p>请看下面这个示例,其使用了前一个示例中<code>Resolution</code>结构体:</p>
|
||||||
|
<pre><code>let hd = Resolution(width: 1920, height: 1080)
|
||||||
|
var cinema = hd
|
||||||
|
</code></pre><p>在以上示例中,声明了一个名为<code>hd</code>的常量,其值为一个初始化为全高清视频分辨率(1920像素宽,1080像素高)的<code>Resolution</code>实例。</p>
|
||||||
|
<p>然后示例中又声明了一个名为<code>cinema</code>的变量,其值为之前声明的<code>hd</code>。因为<code>Resolution</code>是一个结构体,所以<code>cinema</code>的值其实是<code>hd</code>的一个拷贝副本,而不是<code>hd</code>本身。尽管<code>hd</code>和<code>cinema</code>有着相同的宽(width)和高(height)属性,但是在后台中,它们是两个完全不同的实例。</p>
|
||||||
|
<p>下面,为了符合数码影院放映的需求(2048像素宽,1080像素高),<code>cinema</code>的<code>width</code>属性需要作如下修改:</p>
|
||||||
|
<pre><code>cinema.width = 2048
|
||||||
|
</code></pre><p>这里,将会显示<code>cinema</code>的<code>width</code>属性确已改为了<code>2048</code>:</p>
|
||||||
|
<pre><code>println("cinema is now \(cinema.width) pixels wide")
|
||||||
|
// prints "cinema is now 2048 pixels wide"
|
||||||
|
</code></pre><p>然而,初始的<code>hd</code>实例中<code>width</code>属性还是<code>1920</code>:</p>
|
||||||
|
<pre><code>println("hd is still \(hd.width ) pixels wide")
|
||||||
|
// prints "hd is still 1920 pixels wide"
|
||||||
|
</code></pre><p>在将<code>hd</code>赋予给<code>cinema</code>的时候,实际上是将<code>hd</code>中所储存的<code>值(values)</code>进行拷贝,然后将拷贝的数据储存到新的<code>cinema</code>实例中。结果就是两个完全独立的实例碰巧包含有相同的数值。由于两者相互独立,因此将<code>cinema</code>的<code>width</code>修改为<code>2048</code>并不会影响<code>hd</code>中的宽(width)。</p>
|
||||||
|
<p>枚举也遵循相同的行为准则:</p>
|
||||||
|
<pre><code>enum CompassPoint {
|
||||||
|
case North, South, East, West
|
||||||
|
}
|
||||||
|
var currentDirection = CompassPoint.West
|
||||||
|
let rememberedDirection = currentDirection
|
||||||
|
currentDirection = .East
|
||||||
|
if rememberDirection == .West {
|
||||||
|
println("The remembered direction is still .West")
|
||||||
|
}
|
||||||
|
// prints "The remembered direction is still .West"
|
||||||
|
</code></pre><p>上例中<code>rememberedDirection</code>被赋予了<code>currentDirection</code>的值(value),实际上它被赋予的是值(value)的一个拷贝。赋值过程结束后再修改<code>currentDirection</code>的值并不影响<code>rememberedDirection</code>所储存的原始值(value)的拷贝。</p>
|
||||||
|
<h3 id="-">类是引用类型</h3>
|
||||||
|
<p>与值类型不同,引用类型在被赋予到一个变量,常量或者被传递到一个函数时,操作的并不是其拷贝。因此,引用的是已存在的实例本身而不是其拷贝。</p>
|
||||||
|
<p>请看下面这个示例,其使用了之前定义的<code>VideoMode</code>类:</p>
|
||||||
|
<pre><code>let tenEighty = VideoMode()
|
||||||
|
tenEighty.resolution = hd
|
||||||
|
tenEighty.interlaced = true
|
||||||
|
tenEighty.name = "1080i"
|
||||||
|
tenEighty.frameRate = 25.0
|
||||||
|
</code></pre><p>以上示例中,声明了一个名为<code>tenEighty</code>的常量,其引用了一个<code>VideoMode</code>类的新实例。在之前的示例中,这个视频模式(video mode)被赋予了HD分辨率(1920*1080)的一个拷贝(<code>hd</code>)。同时设置为交错(interlaced),命名为<code>“1080i”</code>。最后,其帧率是<code>25.0</code>帧每秒。</p>
|
||||||
|
<p>然后,<code>tenEighty</code> 被赋予名为<code>alsoTenEighty</code>的新常量,同时对<code>alsoTenEighty</code>的帧率进行修改:</p>
|
||||||
|
<pre><code>let alsoTenEighty = tenEighty
|
||||||
|
alsoTenEighty.frameRate = 30.0
|
||||||
|
</code></pre><p>因为类是引用类型,所以<code>tenEight</code>和<code>alsoTenEight</code>实际上引用的是相同的<code>VideoMode</code>实例。换句话说,它们只是同一个实例的两种叫法。</p>
|
||||||
|
<p>下面,通过查看<code>tenEighty</code>的<code>frameRate</code>属性,我们会发现它正确的显示了基本<code>VideoMode</code>实例的新帧率,其值为<code>30.0</code>:</p>
|
||||||
|
<pre><code>println("The frameRate property of tenEighty is now \(tenEighty.frameRate)")
|
||||||
|
// prints "The frameRate property of theEighty is now 30.0"
|
||||||
|
</code></pre><p>需要注意的是<code>tenEighty</code>和<code>alsoTenEighty</code>被声明为<em>常量(constants)</em>而不是变量。然而你依然可以改变<code>tenEighty.frameRate</code>和<code>alsoTenEighty.frameRate</code>,因为这两个常量本身不会改变。它们并不<code>储存</code>这个<code>VideoMode</code>实例,在后台仅仅是对<code>VideoMode</code>实例的引用。所以,改变的是被引用的基础<code>VideoMode</code>的<code>frameRate</code>参数,而不改变常量的值。</p>
|
||||||
|
<h3 id="-">恒等运算符</h3>
|
||||||
|
<p>因为类是引用类型,有可能有多个常量和变量在后台同时引用某一个类实例。(对于结构体和枚举来说,这并不成立。因为它们作值类型,在被赋予到常量,变量或者传递到函数时,总是会被拷贝。)</p>
|
||||||
|
<p>如果能够判定两个常量或者变量是否引用同一个类实例将会很有帮助。为了达到这个目的,Swift 内建了两个恒等运算符:</p>
|
||||||
|
<ul>
|
||||||
|
<li>等价于 ( === )</li>
|
||||||
|
<li>不等价于 ( !== )</li>
|
||||||
|
</ul>
|
||||||
|
<p>以下是运用这两个运算符检测两个常量或者变量是否引用同一个实例:</p>
|
||||||
|
<pre><code>if tenEighty === alsoTenTighty {
|
||||||
|
println("tenTighty and alsoTenEighty refer to the same Resolution instance.")
|
||||||
|
}
|
||||||
|
//prints "tenEighty and alsoTenEighty refer to the same Resolution instance."
|
||||||
|
</code></pre><p>请注意“等价于”(用三个等号表示,===) 与“等于”(用两个等号表示,==)的不同:</p>
|
||||||
|
<ul>
|
||||||
|
<li>“等价于”表示两个类类型(class type)的常量或者变量引用同一个类实例。</li>
|
||||||
|
<li>“等于”表示两个实例的值“相等”或“相同”,判定时要遵照类设计者定义定义的评判标准,因此相比于“相等”,这是一种更加合适的叫法。</li>
|
||||||
|
</ul>
|
||||||
|
<p>当你在定义你的自定义类和结构体的时候,你有义务来决定判定两个实例“相等”的标准。在章节<a href="http://" target="_blank">Equivalence Operators</a>中将会详细介绍实现自定义“等于”和“不等于”运算符的流程。</p>
|
||||||
|
<h3 id="-">指针</h3>
|
||||||
|
<p>如果你有C,C++或者Objective-C语言的经验,那么你也许会知道这些语言使用指针来引用内存中的地址。一个Swift 常量或者变量引用一个引用类型的实例与C语言中的指针类似,不同的是并不直接指向内存中的某个地址,而且也不要求你使用星号(*)来表明你在创建一个引用。Swift 中这些引用与其它的常量或变量的定义方式相同。</p>
|
||||||
|
<h3 id="-">类和结构体的选择</h3>
|
||||||
|
<p>在你的代码中,你可以使用类和结构体来定义你的自定义数据类型。</p>
|
||||||
|
<p>然而,结构体实例总是通过值传递,类实例总是通过引用传递。这意味两者适用不同的任务。当你的在考虑一个工程项目的数据构造和功能的时候,你需要决定每个数据构造是定义成类还是结构体。</p>
|
||||||
|
<p>按照通用的准则,当符合一条或多条以下条件时,请考虑构建结构体:</p>
|
||||||
|
<ul>
|
||||||
|
<li>结构体的主要目的是用来封装少量相关简单数据值。</li>
|
||||||
|
<li>有理由预计一个结构体实例在赋值或传递时,封装的数据将会被拷贝而不是被引用。</li>
|
||||||
|
<li>任何在结构体中储存的值类型属性,也将会被拷贝,而不是被引用。</li>
|
||||||
|
<li>结构体不需要去继承另一个已存在类型的属性或者行为。</li>
|
||||||
|
</ul>
|
||||||
|
<p>合适的结构体候选者包括:</p>
|
||||||
|
<ul>
|
||||||
|
<li>几何形状的大小,封装一个<code>width</code>属性和<code>height</code>属性,两者均为<code>Double</code>类型。</li>
|
||||||
|
<li>一定范围内的路径,封装一个<code>start</code>属性和<code>length</code>属性,两者均为<code>Int</code>类型。</li>
|
||||||
|
<li>三维坐标系内一点,封装<code>x</code>,<code>y</code>和<code>z</code>属性,三者均为<code>Double</code>类型。</li>
|
||||||
|
</ul>
|
||||||
|
<p>在所有其它案例中,定义一个类,生成一个它的实例,并通过引用来管理和传递。实际中,这意味着绝大部分的自定义数据构造都应该是类,而非结构体。</p>
|
||||||
|
<h3 id="-collection-">集合(Collection)类型的赋值和拷贝行为</h3>
|
||||||
|
<p>Swift 中<code>数组(Array)</code>和<code>字典(Dictionary)</code>类型均以结构体的形式实现。然而当数组被赋予一个常量或变量,或被传递给一个函数或方法时,其拷贝行为与字典和其它结构体有些许不同。</p>
|
||||||
|
<p>以下对<code>数组</code>和<code>结构体</code>的行为描述与对<code>NSArray</code>和<code>NSDictionary</code>的行为描述在本质上不同,后者是以类的形式实现,前者是以结构体的形式实现。<code>NSArray</code>和<code>NSDictionary</code>实例总是以对已有实例引用,而不是拷贝的方式被赋值和传递。</p>
|
||||||
|
<blockquote>
|
||||||
|
<p>以下是对于数组,字典,字符串和其它值的<code>拷贝</code>的描述。
|
||||||
|
在你的代码中,拷贝好像是确实是在有拷贝行为的地方产生过。然而,在Swift 的后台中,只有确有必要,<code>实际(actual)</code>拷贝才会被执行。Swift 管理所有的值拷贝以确保性能最优化的性能,所以你也没有必要去避免赋值以保证最优性能。(实际赋值由系统管理优化)</p>
|
||||||
|
</blockquote>
|
||||||
|
<h3 id="-">字典类型的赋值和拷贝行为</h3>
|
||||||
|
<p>无论何时将一个<code>字典</code>实例赋给一个常量或变量,或者传递给一个函数或方法,这个字典会即会在赋值或调用发生时被拷贝。在章节<a href="http://" target="_blank">Structures and Enumerations Are Value Types</a>中将会对此过程进行详细介绍。</p>
|
||||||
|
<p>如果<code>字典</code>实例中所储存的键(keys)和/或值(values)是值类型(结构体或枚举),当赋值或调用发生时,它们都会被拷贝。相反,如果键(keys)和/或值(values)是引用类型,被拷贝的将会是引用,而不是被它们引用的类实例或函数。<code>字典</code>的键和值的拷贝行为与结构体所储存的属性的拷贝行为相同。</p>
|
||||||
|
<p>下面的示例定义了一个名为<code>ages</code>的字典,其中储存了四个人的名字和年龄。<code>ages</code>字典被赋予了一个名为<code>copiedAges</code>的新变量,同时<code>ages</code>在赋值的过程中被拷贝。赋值结束后,<code>ages</code>和<code>copiedAges</code>成为两个相互独立的字典。</p>
|
||||||
|
<pre><code>var ages = ["Peter": 23, "Wei": 35, "Anish": 65, "Katya": 19]
|
||||||
|
var copiedAges = ages
|
||||||
|
</code></pre><p>这个字典的键(keys)是<code>字符串(String)</code>类型,值(values)是<code>整(Int)</code>类型。这两种类型在Swift 中都是值类型(value types),所以当字典被拷贝时,两者都会被拷贝。</p>
|
||||||
|
<p>我们可以通过改变一个字典中的年龄值(age value),检查另一个字典中所对应的值,来证明<code>ages</code>字典确实是被拷贝了。如果在<code>copiedAges</code>字典中将<code>Peter</code>的值设为<code>24</code>,那么<code>ages</code>字典仍然会返回修改前的值<code>23</code>:</p>
|
||||||
|
<pre><code>copiedAges["Peter"] = 24
|
||||||
|
println(ages["Peter"])
|
||||||
|
// prints "23"
|
||||||
|
</code></pre><h3 id="-">数组的赋值和拷贝行为</h3>
|
||||||
|
<p>在Swift 中,<code>数组(Arrays)</code>类型的赋值和拷贝行为要比<code>字典(Dictionary)</code>类型的复杂的多。当操作数组内容时,<code>数组(Array)</code>能提供接近C语言的的性能,并且拷贝行为只有在必要时才会发生。</p>
|
||||||
|
<p>如果你将一个<code>数组(Array)</code>实例赋给一个变量或常量,或者将其作为参数传递给函数或方法调用,在事件发生时数组的内容<code>不</code>会被拷贝。相反,数组公用相同的元素序列。当你在一个数组内修改某一元素,修改结果也会在另一数组显示。</p>
|
||||||
|
<p>对数组来说,拷贝行为仅仅当操作有可能修改数组<code>长度</code>时才会发生。这种行为包括了附加(appending),插入(inserting),删除(removing)或者使用范围下标(ranged subscript)去替换这一范围内的元素。只有当数组拷贝确要发生时,数组内容的行为规则与字典中键值的相同,参见章节<a href="http://" target="_blank">Assignment and Copy Behavior for Dictionaries</a>。</p>
|
||||||
|
<p>下面的示例将一个<code>整数(Int)</code>数组赋给了一个名为<code>a</code>的变量,继而又被赋给了变量<code>b</code>和<code>c</code>:</p>
|
||||||
|
<pre><code>var a = [1, 2, 3]
|
||||||
|
var b = a
|
||||||
|
var c = a
|
||||||
|
</code></pre><p>我们可以在<code>a</code>,<code>b</code>,<code>c</code>上使用下标语法以得到数组的第一个元素:</p>
|
||||||
|
<pre><code>println(a[0])
|
||||||
|
// 1
|
||||||
|
println(b[0])
|
||||||
|
// 1
|
||||||
|
println(c[0])
|
||||||
|
// 1
|
||||||
|
</code></pre><p>如果通过下标语法修改数组中某一元素的值,那么<code>a</code>,<code>b</code>,<code>c</code>中的相应值都会发生改变。请注意当你用下标语法修改某一值时,并没有拷贝行为伴随发生,因为下表语法修改值时没有改变数组长度的可能:</p>
|
||||||
|
<pre><code>a[0] = 42
|
||||||
|
println(a[0])
|
||||||
|
// 42
|
||||||
|
println(b[0])
|
||||||
|
// 42
|
||||||
|
println(c[0])
|
||||||
|
// 42
|
||||||
|
</code></pre><p>然而,当你给<code>a</code>附加新元素时,数组的长度<code>会</code>改变。
|
||||||
|
当附加元素这一事件发生时,Swift 语言会创建这个数组的一个拷贝。从此以后,<code>a</code>将会是原数组的一个独立拷贝。</p>
|
||||||
|
<p>拷贝发生后,如果再修改<code>a</code>中元素值的话,<code>a</code>将会返回与<code>b</code>,<code>c</code>不同的结果,因为后两者引用的是原来的数组:</p>
|
||||||
|
<pre><code>a.append(4)
|
||||||
|
a[0] = 777
|
||||||
|
println(a[0])
|
||||||
|
// 777
|
||||||
|
println(b[0])
|
||||||
|
// 42
|
||||||
|
println(c[0])
|
||||||
|
// 42
|
||||||
|
</code></pre><h3 id="-">确保数组的唯一性</h3>
|
||||||
|
<p>在操作一个数组,或将其传递给函数以及方法调用之前是很有必要先确定这个数组是有一个唯一拷贝的。通过在数组变量上调用<code>unshare</code>方法来确定数组引用的唯一性。(当数组赋给常量时,不能调用<code>unshare</code>方法)</p>
|
||||||
|
<p>如果一个数组被多个变量引用,在其中的一个变量上调用<code>unshare</code>方法,则会拷贝此数组,此时这个变量将会有属于它自己的独立数组拷贝。当数组仅被一个变量引用时,则不会有拷贝发生。</p>
|
||||||
|
<p>在上一个示例的最后,<code>b</code>和<code>c</code>都引用了同一个数组。此时在<code>b</code>上调用<code>unshare</code>方法则会将<code>b</code>变成一个唯一个拷贝:</p>
|
||||||
|
<pre><code>b.unshare()
|
||||||
|
</code></pre><p>在<code>unshare</code>方法调用后再修改<code>b</code>中第一个元素的值,这三个数组(<code>a</code>,<code>b</code>,<code>c</code>)会返回不同的三个值:</p>
|
||||||
|
<pre><code>b[0] = -105
|
||||||
|
println(a[0])
|
||||||
|
// 77
|
||||||
|
println(b[0])
|
||||||
|
// -105
|
||||||
|
println(c[0])
|
||||||
|
// 42
|
||||||
|
</code></pre><h3 id="-">判定两个数组是否共用相同元素</h3>
|
||||||
|
<p>我们通过使用恒等运算符(identity operators)( === and !==)来判定两个数组或子数组共用相同的储存空间或元素。</p>
|
||||||
|
<p>下面这个示例使用了“恒等于(identical to)” 运算符(===) 来判定<code>b</code>和<code>c</code>是否共用相同的数组元素:</p>
|
||||||
|
<pre><code>if b === c {
|
||||||
|
println("b and c still share the same array elements.")
|
||||||
|
} else {
|
||||||
|
println("b and c now refer to two independent sets of array elements.")
|
||||||
|
}
|
||||||
|
|
||||||
|
// prints "b and c now refer totwo independent sets of array elements."
|
||||||
|
</code></pre><p>此外,我们还可以使用恒等运算符来判定两个子数组是否共用相同的元素。下面这个示例中,比较了<code>b</code>的两个相等的子数组,并且确定了这两个子数组都引用相同的元素:</p>
|
||||||
|
<pre><code>if b[0...1] === b[0...1] {
|
||||||
|
println("These two subarrays share the same elements.")
|
||||||
|
} else {
|
||||||
|
println("These two subarrays do not share the same elements.")
|
||||||
|
}
|
||||||
|
// prints "These two subarrays share the same elements."
|
||||||
|
</code></pre><h3 id="-">强制复制数组</h3>
|
||||||
|
<p>我们通过调用数组的<code>copy</code>方法进行强制显性复制。这个方法对数组进行了浅拷贝(shallow copy),并且返回一个包含此拷贝的新数组。</p>
|
||||||
|
<p>下面这个示例中定义了一个<code>names</code>数组,其包含了七个人名。还定义了一个<code>copiedNames</code>变量,用以储存在<code>names</code>上调用<code>copy</code>方法所返回的结果:</p>
|
||||||
|
<pre><code>var names = ["Mohsen", "Hilary", "Justyn", "Amy", "Rich", "Graham", "Vic"]
|
||||||
|
var copiedNames = names.copy
|
||||||
|
</code></pre><p>我们可以通过修改一个数组中某元素,并且检查另一个数组中对应元素的方法来判定<code>names</code>数组确已被复制。如果你将<code>copiedNames</code>中第一个元素从"<code>Mohsen</code>"修改为"<code>Mo</code>",则<code>names</code>数组返回的仍是拷贝发生前的"<code>Mohsen</code>":</p>
|
||||||
|
<pre><code>copiedName[0] = "Mo"
|
||||||
|
println(name[0])
|
||||||
|
// prints "Mohsen"
|
||||||
|
</code></pre><blockquote>
|
||||||
|
<p>如果你仅需要确保你对数组的引用是唯一引用,请调用<code>unshare</code>方法,而不是<code>copy</code>方法。<code>unshare</code>方法仅会在确有必要时才会创建数组拷贝。<code>copy</code>方法会在任何时候都创建一个新的拷贝,即使引用已经是唯一引用。</p>
|
||||||
|
</blockquote>
|
||||||
|
|
||||||
|
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
@ -46,7 +46,7 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
<div class="book" data-level="2.10" data-basepath=".." data-revision="1402451678088">
|
<div class="book" data-level="2.10" data-basepath=".." data-revision="1402469309776">
|
||||||
<div class="book-header">
|
<div class="book-header">
|
||||||
<!-- Actions Left -->
|
<!-- Actions Left -->
|
||||||
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
||||||
@ -587,7 +587,7 @@
|
|||||||
|
|
||||||
<div class="page-inner">
|
<div class="page-inner">
|
||||||
|
|
||||||
<section class="normal" id="section-gitbook_141">
|
<section class="normal" id="section-gitbook_41">
|
||||||
|
|
||||||
<h1 id="-properties-">属性 (Properties)</h1>
|
<h1 id="-properties-">属性 (Properties)</h1>
|
||||||
<hr>
|
<hr>
|
||||||
|
|||||||
@ -46,7 +46,7 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
<div class="book" data-level="2.11" data-basepath=".." data-revision="1402451678088">
|
<div class="book" data-level="2.11" data-basepath=".." data-revision="1402469309776">
|
||||||
<div class="book-header">
|
<div class="book-header">
|
||||||
<!-- Actions Left -->
|
<!-- Actions Left -->
|
||||||
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
||||||
@ -587,7 +587,7 @@
|
|||||||
|
|
||||||
<div class="page-inner">
|
<div class="page-inner">
|
||||||
|
|
||||||
<section class="normal" id="section-gitbook_143">
|
<section class="normal" id="section-gitbook_43">
|
||||||
|
|
||||||
<h1 id="-methods-">方法(Methods)</h1>
|
<h1 id="-methods-">方法(Methods)</h1>
|
||||||
<hr>
|
<hr>
|
||||||
|
|||||||
@ -46,7 +46,7 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
<div class="book" data-level="2.12" data-basepath=".." data-revision="1402451678088">
|
<div class="book" data-level="2.12" data-basepath=".." data-revision="1402469309776">
|
||||||
<div class="book-header">
|
<div class="book-header">
|
||||||
<!-- Actions Left -->
|
<!-- Actions Left -->
|
||||||
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
||||||
@ -587,7 +587,7 @@
|
|||||||
|
|
||||||
<div class="page-inner">
|
<div class="page-inner">
|
||||||
|
|
||||||
<section class="normal" id="section-gitbook_145">
|
<section class="normal" id="section-gitbook_45">
|
||||||
|
|
||||||
<h1 id="-subscripts-">下标(Subscripts)</h1>
|
<h1 id="-subscripts-">下标(Subscripts)</h1>
|
||||||
<hr>
|
<hr>
|
||||||
|
|||||||
@ -46,7 +46,7 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
<div class="book" data-level="2.13" data-basepath=".." data-revision="1402451678088">
|
<div class="book" data-level="2.13" data-basepath=".." data-revision="1402469309776">
|
||||||
<div class="book-header">
|
<div class="book-header">
|
||||||
<!-- Actions Left -->
|
<!-- Actions Left -->
|
||||||
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
||||||
@ -587,7 +587,7 @@
|
|||||||
|
|
||||||
<div class="page-inner">
|
<div class="page-inner">
|
||||||
|
|
||||||
<section class="normal" id="section-gitbook_110">
|
<section class="normal" id="section-gitbook_10">
|
||||||
|
|
||||||
<h1 id="-">继承</h1>
|
<h1 id="-">继承</h1>
|
||||||
<hr>
|
<hr>
|
||||||
|
|||||||
@ -46,7 +46,7 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
<div class="book" data-level="2.14" data-basepath=".." data-revision="1402451678088">
|
<div class="book" data-level="2.14" data-basepath=".." data-revision="1402469309776">
|
||||||
<div class="book-header">
|
<div class="book-header">
|
||||||
<!-- Actions Left -->
|
<!-- Actions Left -->
|
||||||
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
||||||
|
|||||||
@ -46,7 +46,7 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
<div class="book" data-level="2.15" data-basepath=".." data-revision="1402451678088">
|
<div class="book" data-level="2.15" data-basepath=".." data-revision="1402469309776">
|
||||||
<div class="book-header">
|
<div class="book-header">
|
||||||
<!-- Actions Left -->
|
<!-- Actions Left -->
|
||||||
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
||||||
@ -587,7 +587,7 @@
|
|||||||
|
|
||||||
<div class="page-inner">
|
<div class="page-inner">
|
||||||
|
|
||||||
<section class="normal" id="section-gitbook_150">
|
<section class="normal" id="section-gitbook_50">
|
||||||
|
|
||||||
<h1 id="-">析构过程</h1>
|
<h1 id="-">析构过程</h1>
|
||||||
<hr>
|
<hr>
|
||||||
|
|||||||
@ -46,7 +46,7 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
<div class="book" data-level="2.16" data-basepath=".." data-revision="1402451678088">
|
<div class="book" data-level="2.16" data-basepath=".." data-revision="1402469309776">
|
||||||
<div class="book-header">
|
<div class="book-header">
|
||||||
<!-- Actions Left -->
|
<!-- Actions Left -->
|
||||||
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
||||||
@ -587,7 +587,7 @@
|
|||||||
|
|
||||||
<div class="page-inner">
|
<div class="page-inner">
|
||||||
|
|
||||||
<section class="normal" id="section-gitbook_152">
|
<section class="normal" id="section-gitbook_52">
|
||||||
|
|
||||||
<h1 id="-">自动引用计数</h1>
|
<h1 id="-">自动引用计数</h1>
|
||||||
<hr>
|
<hr>
|
||||||
|
|||||||
@ -46,7 +46,7 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
<div class="book" data-level="2.17" data-basepath=".." data-revision="1402451678088">
|
<div class="book" data-level="2.17" data-basepath=".." data-revision="1402469309776">
|
||||||
<div class="book-header">
|
<div class="book-header">
|
||||||
<!-- Actions Left -->
|
<!-- Actions Left -->
|
||||||
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
||||||
@ -587,7 +587,7 @@
|
|||||||
|
|
||||||
<div class="page-inner">
|
<div class="page-inner">
|
||||||
|
|
||||||
<section class="normal" id="section-gitbook_154">
|
<section class="normal" id="section-gitbook_54">
|
||||||
|
|
||||||
<h1 id="optional-chaining">Optional Chaining</h1>
|
<h1 id="optional-chaining">Optional Chaining</h1>
|
||||||
<hr>
|
<hr>
|
||||||
|
|||||||
@ -46,7 +46,7 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
<div class="book" data-level="2.18" data-basepath=".." data-revision="1402451678088">
|
<div class="book" data-level="2.18" data-basepath=".." data-revision="1402469309776">
|
||||||
<div class="book-header">
|
<div class="book-header">
|
||||||
<!-- Actions Left -->
|
<!-- Actions Left -->
|
||||||
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
||||||
@ -587,7 +587,7 @@
|
|||||||
|
|
||||||
<div class="page-inner">
|
<div class="page-inner">
|
||||||
|
|
||||||
<section class="normal" id="section-gitbook_156">
|
<section class="normal" id="section-gitbook_56">
|
||||||
|
|
||||||
<h1 id="-type-casting-">类型检查(Type Casting)</h1>
|
<h1 id="-type-casting-">类型检查(Type Casting)</h1>
|
||||||
<hr>
|
<hr>
|
||||||
|
|||||||
@ -46,7 +46,7 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
<div class="book" data-level="2.19" data-basepath=".." data-revision="1402451678088">
|
<div class="book" data-level="2.19" data-basepath=".." data-revision="1402469309776">
|
||||||
<div class="book-header">
|
<div class="book-header">
|
||||||
<!-- Actions Left -->
|
<!-- Actions Left -->
|
||||||
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
||||||
@ -587,7 +587,7 @@
|
|||||||
|
|
||||||
<div class="page-inner">
|
<div class="page-inner">
|
||||||
|
|
||||||
<section class="normal" id="section-gitbook_158">
|
<section class="normal" id="section-gitbook_58">
|
||||||
|
|
||||||
<h1 id="-">类型嵌套</h1>
|
<h1 id="-">类型嵌套</h1>
|
||||||
<hr>
|
<hr>
|
||||||
|
|||||||
@ -46,7 +46,7 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
<div class="book" data-level="2.20" data-basepath=".." data-revision="1402451678088">
|
<div class="book" data-level="2.20" data-basepath=".." data-revision="1402469309776">
|
||||||
<div class="book-header">
|
<div class="book-header">
|
||||||
<!-- Actions Left -->
|
<!-- Actions Left -->
|
||||||
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
||||||
@ -587,7 +587,7 @@
|
|||||||
|
|
||||||
<div class="page-inner">
|
<div class="page-inner">
|
||||||
|
|
||||||
<section class="normal" id="section-gitbook_160">
|
<section class="normal" id="section-gitbook_60">
|
||||||
|
|
||||||
<h1 id="-extensions-">扩展(Extensions)</h1>
|
<h1 id="-extensions-">扩展(Extensions)</h1>
|
||||||
<hr>
|
<hr>
|
||||||
|
|||||||
@ -46,7 +46,7 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
<div class="book" data-level="2.21" data-basepath=".." data-revision="1402451678088">
|
<div class="book" data-level="2.21" data-basepath=".." data-revision="1402469309776">
|
||||||
<div class="book-header">
|
<div class="book-header">
|
||||||
<!-- Actions Left -->
|
<!-- Actions Left -->
|
||||||
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
||||||
@ -587,7 +587,7 @@
|
|||||||
|
|
||||||
<div class="page-inner">
|
<div class="page-inner">
|
||||||
|
|
||||||
<section class="normal" id="section-gitbook_162">
|
<section class="normal" id="section-gitbook_62">
|
||||||
|
|
||||||
<h1 id="-">协议</h1>
|
<h1 id="-">协议</h1>
|
||||||
<hr>
|
<hr>
|
||||||
|
|||||||
@ -46,7 +46,7 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
<div class="book" data-level="2.22" data-basepath=".." data-revision="1402451678088">
|
<div class="book" data-level="2.22" data-basepath=".." data-revision="1402469309776">
|
||||||
<div class="book-header">
|
<div class="book-header">
|
||||||
<!-- Actions Left -->
|
<!-- Actions Left -->
|
||||||
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
||||||
@ -587,7 +587,7 @@
|
|||||||
|
|
||||||
<div class="page-inner">
|
<div class="page-inner">
|
||||||
|
|
||||||
<section class="normal" id="section-gitbook_164">
|
<section class="normal" id="section-gitbook_64">
|
||||||
|
|
||||||
<h1 id="-">泛型</h1>
|
<h1 id="-">泛型</h1>
|
||||||
<hr>
|
<hr>
|
||||||
|
|||||||
@ -46,7 +46,7 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
<div class="book" data-level="2.23" data-basepath=".." data-revision="1402451678088">
|
<div class="book" data-level="2.23" data-basepath=".." data-revision="1402469309776">
|
||||||
<div class="book-header">
|
<div class="book-header">
|
||||||
<!-- Actions Left -->
|
<!-- Actions Left -->
|
||||||
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
||||||
@ -587,7 +587,7 @@
|
|||||||
|
|
||||||
<div class="page-inner">
|
<div class="page-inner">
|
||||||
|
|
||||||
<section class="normal" id="section-gitbook_167">
|
<section class="normal" id="section-gitbook_68">
|
||||||
|
|
||||||
<p>In addition to the operators described in <a href="Basic Operators">Basic Operators</a>, Swift provides several advanced operators that perform more complex value manipulation. These include all of the bitwise and bit shifting operators you will be familiar with from C and Objective-C.</p>
|
<p>In addition to the operators described in <a href="Basic Operators">Basic Operators</a>, Swift provides several advanced operators that perform more complex value manipulation. These include all of the bitwise and bit shifting operators you will be familiar with from C and Objective-C.</p>
|
||||||
<p>除于<a href="Basic Operators">基本操作符</a>中所讲的运算符, Swift还有许多复杂的高级运算符, 包括了C语和Objective-C中的位运算符和位移运算.</p>
|
<p>除于<a href="Basic Operators">基本操作符</a>中所讲的运算符, Swift还有许多复杂的高级运算符, 包括了C语和Objective-C中的位运算符和位移运算.</p>
|
||||||
|
|||||||
@ -46,7 +46,7 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
<div class="book" data-level="2" data-basepath=".." data-revision="1402451678088">
|
<div class="book" data-level="2" data-basepath=".." data-revision="1402469309776">
|
||||||
<div class="book-header">
|
<div class="book-header">
|
||||||
<!-- Actions Left -->
|
<!-- Actions Left -->
|
||||||
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
||||||
@ -587,7 +587,7 @@
|
|||||||
|
|
||||||
<div class="page-inner">
|
<div class="page-inner">
|
||||||
|
|
||||||
<section class="normal" id="section-gitbook_168">
|
<section class="normal" id="section-gitbook_67">
|
||||||
|
|
||||||
<h1 id="swift-">Swift 教程</h1>
|
<h1 id="swift-">Swift 教程</h1>
|
||||||
<p>本章介绍了 Swift 的各种特性及其使用方法,是全书的核心部分。</p>
|
<p>本章介绍了 Swift 的各种特性及其使用方法,是全书的核心部分。</p>
|
||||||
|
|||||||
@ -46,7 +46,7 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
<div class="book" data-level="3.1" data-basepath=".." data-revision="1402451678088">
|
<div class="book" data-level="3.1" data-basepath=".." data-revision="1402469309776">
|
||||||
<div class="book-header">
|
<div class="book-header">
|
||||||
<!-- Actions Left -->
|
<!-- Actions Left -->
|
||||||
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
||||||
@ -587,7 +587,7 @@
|
|||||||
|
|
||||||
<div class="page-inner">
|
<div class="page-inner">
|
||||||
|
|
||||||
<section class="normal" id="section-gitbook_171">
|
<section class="normal" id="section-gitbook_71">
|
||||||
|
|
||||||
<h1 id="-">关于语言附注</h1>
|
<h1 id="-">关于语言附注</h1>
|
||||||
<hr>
|
<hr>
|
||||||
|
|||||||
@ -46,7 +46,7 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
<div class="book" data-level="3.2" data-basepath=".." data-revision="1402451678088">
|
<div class="book" data-level="3.2" data-basepath=".." data-revision="1402469309776">
|
||||||
<div class="book-header">
|
<div class="book-header">
|
||||||
<!-- Actions Left -->
|
<!-- Actions Left -->
|
||||||
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
||||||
@ -587,7 +587,7 @@
|
|||||||
|
|
||||||
<div class="page-inner">
|
<div class="page-inner">
|
||||||
|
|
||||||
<section class="normal" id="section-gitbook_178">
|
<section class="normal" id="section-gitbook_78">
|
||||||
|
|
||||||
<h1 id="-">语法结构</h1>
|
<h1 id="-">语法结构</h1>
|
||||||
<hr>
|
<hr>
|
||||||
|
|||||||
@ -46,7 +46,7 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
<div class="book" data-level="3.3" data-basepath=".." data-revision="1402451678088">
|
<div class="book" data-level="3.3" data-basepath=".." data-revision="1402469309776">
|
||||||
<div class="book-header">
|
<div class="book-header">
|
||||||
<!-- Actions Left -->
|
<!-- Actions Left -->
|
||||||
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
||||||
@ -587,7 +587,7 @@
|
|||||||
|
|
||||||
<div class="page-inner">
|
<div class="page-inner">
|
||||||
|
|
||||||
<section class="normal" id="section-gitbook_173">
|
<section class="normal" id="section-gitbook_73">
|
||||||
|
|
||||||
<h1 id="-types-">类型(Types)</h1>
|
<h1 id="-types-">类型(Types)</h1>
|
||||||
<hr>
|
<hr>
|
||||||
|
|||||||
@ -46,7 +46,7 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
<div class="book" data-level="3.4" data-basepath=".." data-revision="1402451678088">
|
<div class="book" data-level="3.4" data-basepath=".." data-revision="1402469309776">
|
||||||
<div class="book-header">
|
<div class="book-header">
|
||||||
<!-- Actions Left -->
|
<!-- Actions Left -->
|
||||||
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
||||||
@ -587,7 +587,7 @@
|
|||||||
|
|
||||||
<div class="page-inner">
|
<div class="page-inner">
|
||||||
|
|
||||||
<section class="normal" id="section-gitbook_175">
|
<section class="normal" id="section-gitbook_75">
|
||||||
|
|
||||||
<h1 id="-expressions-">表达式(Expressions)</h1>
|
<h1 id="-expressions-">表达式(Expressions)</h1>
|
||||||
<hr>
|
<hr>
|
||||||
|
|||||||
@ -46,7 +46,7 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
<div class="book" data-level="3.6" data-basepath=".." data-revision="1402451678088">
|
<div class="book" data-level="3.6" data-basepath=".." data-revision="1402469309776">
|
||||||
<div class="book-header">
|
<div class="book-header">
|
||||||
<!-- Actions Left -->
|
<!-- Actions Left -->
|
||||||
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
||||||
|
|||||||
@ -46,7 +46,7 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
<div class="book" data-level="3.7" data-basepath=".." data-revision="1402451678088">
|
<div class="book" data-level="3.7" data-basepath=".." data-revision="1402469309776">
|
||||||
<div class="book-header">
|
<div class="book-header">
|
||||||
<!-- Actions Left -->
|
<!-- Actions Left -->
|
||||||
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
||||||
@ -587,7 +587,7 @@
|
|||||||
|
|
||||||
<div class="page-inner">
|
<div class="page-inner">
|
||||||
|
|
||||||
<section class="normal" id="section-gitbook_169">
|
<section class="normal" id="section-gitbook_69">
|
||||||
|
|
||||||
<h1 id="-">特性</h1>
|
<h1 id="-">特性</h1>
|
||||||
<hr>
|
<hr>
|
||||||
|
|||||||
@ -46,7 +46,7 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
<div class="book" data-level="3.8" data-basepath=".." data-revision="1402451678088">
|
<div class="book" data-level="3.8" data-basepath=".." data-revision="1402469309776">
|
||||||
<div class="book-header">
|
<div class="book-header">
|
||||||
<!-- Actions Left -->
|
<!-- Actions Left -->
|
||||||
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
||||||
@ -587,7 +587,7 @@
|
|||||||
|
|
||||||
<div class="page-inner">
|
<div class="page-inner">
|
||||||
|
|
||||||
<section class="normal" id="section-gitbook_180">
|
<section class="normal" id="section-gitbook_80">
|
||||||
|
|
||||||
<h1 id="-patterns-">模式(Patterns)</h1>
|
<h1 id="-patterns-">模式(Patterns)</h1>
|
||||||
<hr>
|
<hr>
|
||||||
|
|||||||
@ -46,7 +46,7 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
<div class="book" data-level="3.9" data-basepath=".." data-revision="1402451678088">
|
<div class="book" data-level="3.9" data-basepath=".." data-revision="1402469309776">
|
||||||
<div class="book-header">
|
<div class="book-header">
|
||||||
<!-- Actions Left -->
|
<!-- Actions Left -->
|
||||||
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
||||||
@ -587,7 +587,7 @@
|
|||||||
|
|
||||||
<div class="page-inner">
|
<div class="page-inner">
|
||||||
|
|
||||||
<section class="normal" id="section-gitbook_182">
|
<section class="normal" id="section-gitbook_82">
|
||||||
|
|
||||||
<h1 id="-">泛型参数</h1>
|
<h1 id="-">泛型参数</h1>
|
||||||
<hr>
|
<hr>
|
||||||
|
|||||||
@ -44,7 +44,7 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
<div class="book" data-level="3.10" data-basepath=".." data-revision="1402451678088">
|
<div class="book" data-level="3.10" data-basepath=".." data-revision="1402469309776">
|
||||||
<div class="book-header">
|
<div class="book-header">
|
||||||
<!-- Actions Left -->
|
<!-- Actions Left -->
|
||||||
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
||||||
@ -585,7 +585,7 @@
|
|||||||
|
|
||||||
<div class="page-inner">
|
<div class="page-inner">
|
||||||
|
|
||||||
<section class="normal" id="section-gitbook_184">
|
<section class="normal" id="section-gitbook_84">
|
||||||
|
|
||||||
<h1 id="-">语法总结</h1>
|
<h1 id="-">语法总结</h1>
|
||||||
<hr>
|
<hr>
|
||||||
|
|||||||
@ -46,7 +46,7 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
<div class="book" data-level="3.5" data-basepath=".." data-revision="1402451678088">
|
<div class="book" data-level="3.5" data-basepath=".." data-revision="1402469309776">
|
||||||
<div class="book-header">
|
<div class="book-header">
|
||||||
<!-- Actions Left -->
|
<!-- Actions Left -->
|
||||||
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
||||||
@ -587,7 +587,7 @@
|
|||||||
|
|
||||||
<div class="page-inner">
|
<div class="page-inner">
|
||||||
|
|
||||||
<section class="normal" id="section-gitbook_186">
|
<section class="normal" id="section-gitbook_86">
|
||||||
|
|
||||||
<h1 id="-">语句</h1>
|
<h1 id="-">语句</h1>
|
||||||
<hr>
|
<hr>
|
||||||
|
|||||||
@ -46,7 +46,7 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
<div class="book" data-level="3" data-basepath=".." data-revision="1402451678088">
|
<div class="book" data-level="3" data-basepath=".." data-revision="1402469309776">
|
||||||
<div class="book-header">
|
<div class="book-header">
|
||||||
<!-- Actions Left -->
|
<!-- Actions Left -->
|
||||||
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
||||||
|
|||||||
@ -44,7 +44,7 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
<div class="book" data-level="0" data-basepath="." data-revision="1402451678088">
|
<div class="book" data-level="0" data-basepath="." data-revision="1402469309776">
|
||||||
<div class="book-header">
|
<div class="book-header">
|
||||||
<!-- Actions Left -->
|
<!-- Actions Left -->
|
||||||
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
|
||||||
@ -585,7 +585,7 @@
|
|||||||
|
|
||||||
<div class="page-inner">
|
<div class="page-inner">
|
||||||
|
|
||||||
<section class="normal" id="section-gitbook_104">
|
<section class="normal" id="section-gitbook_4">
|
||||||
|
|
||||||
<h1 id="swift-">Swift 编程语言</h1>
|
<h1 id="swift-">Swift 编程语言</h1>
|
||||||
<p>Swift 是苹果在 WWDC 2014 上发布的一款全新的编程语言,本书译自苹果官方的 Swift 教程《The Swift Programming Language》。</p>
|
<p>Swift 是苹果在 WWDC 2014 上发布的一款全新的编程语言,本书译自苹果官方的 Swift 教程《The Swift Programming Language》。</p>
|
||||||
|
|||||||
@ -1,5 +1,5 @@
|
|||||||
CACHE MANIFEST
|
CACHE MANIFEST
|
||||||
# Revision 1402451678089
|
# Revision 1402469309777
|
||||||
|
|
||||||
CACHE:
|
CACHE:
|
||||||
index.html
|
index.html
|
||||||
@ -13,8 +13,8 @@ chapter2/04_Collection_Types.html
|
|||||||
chapter2/05_Control_Flow.html
|
chapter2/05_Control_Flow.html
|
||||||
chapter2/06_Functions.html
|
chapter2/06_Functions.html
|
||||||
chapter2/07_Closures.html
|
chapter2/07_Closures.html
|
||||||
chapter2/09_Classes_and_Structures.html
|
|
||||||
chapter2/08_Enumerations.html
|
chapter2/08_Enumerations.html
|
||||||
|
chapter2/09_Classes_and_Structures.html
|
||||||
chapter2/10_Properties.html
|
chapter2/10_Properties.html
|
||||||
chapter2/11_Methods.html
|
chapter2/11_Methods.html
|
||||||
chapter2/12_Subscripts.html
|
chapter2/12_Subscripts.html
|
||||||
@ -28,8 +28,8 @@ chapter2/19_Nested_Types.html
|
|||||||
chapter2/20_Extensions.html
|
chapter2/20_Extensions.html
|
||||||
chapter2/21_Protocols.html
|
chapter2/21_Protocols.html
|
||||||
chapter2/22_Generics.html
|
chapter2/22_Generics.html
|
||||||
chapter2/23_Advanced_Operators.html
|
|
||||||
chapter2/chapter2.html
|
chapter2/chapter2.html
|
||||||
|
chapter2/23_Advanced_Operators.html
|
||||||
chapter3/06_Attributes.html
|
chapter3/06_Attributes.html
|
||||||
chapter3/01_About_the_Language_Reference.html
|
chapter3/01_About_the_Language_Reference.html
|
||||||
chapter3/03_Types.html
|
chapter3/03_Types.html
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
@ -1,31 +1,40 @@
|
|||||||
# 基本运算符
|
# 基本运算符
|
||||||
-----------------
|
-----------------
|
||||||
|
|
||||||
运算符是检查, 改变, 合并值的特殊符号或短语. 例如, 加号 `+` 把计算两个数的和(如 `let i = 1 + 2`). 复杂些的运行算包括逻辑与`&&`(如 `if enteredDoorCode && passedRetinaScan`), 还有自增运算符 `++i` 这样让自身加一的便捷运算.
|
本页包含内容:
|
||||||
|
|
||||||
Swift支持大部分标准C语言的运算符, 且改进许多特性来减少常规编码错误. 如, 赋值符 `=` 不返回值, 以防止错把等号 `==` 写成赋值号 `=` 而导致Bug. 数值运算符( `+` , `-`, `*`, `/`, `%`等)会检测并不允许值溢出, 以此来避免保存变量时由于变量大于或小于其类型所能承载的范围时导致的异常结果. 当然允许你选择使用Swift的溢出运算符来玩溢出. 具体使用请移步[溢出运算符](Overflow Operators).
|
- [术语](#terminology)
|
||||||
|
- [赋值运算符](#assignment_operator)
|
||||||
|
- [数值运算符](#arithmetic_operators)
|
||||||
|
- [组合赋值运算符(Compound Assignment Operators)](#compound_assignment_operators)
|
||||||
|
- [比较运算符](#comparison_operators)
|
||||||
|
- [三目条件运算符(Ternary Conditional Operator)](#ternary_conditional_operator)
|
||||||
|
- [区间运算符](#range_operators)
|
||||||
|
- [逻辑运算符](#logical_operators)
|
||||||
|
|
||||||
区别于C语言, 在Swift中你可以对浮点数进行取余运算( `%` ), 还提供了C语言没有的表达两数之间的值的区间运算符, ( `a..b` 和 `a...b` ), 这方便我们表达一个区间内的数值.
|
运算符是检查,改变,合并值的特殊符号或短语。例如,加号`+`把计算两个数的和(如 `let i = 1 + 2`)。复杂些的运行算包括逻辑与`&&`(如 `if enteredDoorCode && passedRetinaScan`),还有自增运算符`++i`这样让自身加一的便捷运算。
|
||||||
|
|
||||||
本章节只描述了Swift中的基本运算符, [高级运算符](http://#)包含了高级运算符,及如何自定义运算符, 及如何进行自定义类型的运算符重载.
|
Swift支持大部分标准C语言的运算符,且改进许多特性来减少常规编码错误。如,赋值符`=`不返回值,以防止错把等号`==`写成赋值号`=`而导致Bug。数值运算符(`+`,`-`,`*`,`/`,`%`等)会检测并不允许值溢出,以此来避免保存变量时由于变量大于或小于其类型所能承载的范围时导致的异常结果。当然允许你选择使用Swift的溢出运算符来玩溢出。具体使用请移步[溢出运算符](23_Advanced_Operators.html#overflow_operators)。
|
||||||
|
|
||||||
# 术语
|
区别于C语言,在Swift中你可以对浮点数进行取余运算(`%`),还提供了C语言没有的表达两数之间的值的区间运算符,(`a..b`和`a...b`),这方便我们表达一个区间内的数值。
|
||||||
|
|
||||||
运算符有一目, 双目和三目运算符.
|
本章节只描述了Swift中的基本运算符,[高级运算符](23_Advanced_Operators.html)包含了高级运算符,及如何自定义运算符,及如何进行自定义类型的运算符重载。
|
||||||
|
|
||||||
一目运算符对单一操作对象操作, 如 `-a`.
|
<a name="terminology"></a>
|
||||||
|
## 术语
|
||||||
|
|
||||||
一目运算符分前置符和后置运算符, 前置运算符需紧排操作对象之前, 如 `!b`, 后置运算符需紧跟操作对象之后,如 `i++`,
|
运算符有一目,双目和三目运算符。
|
||||||
|
|
||||||
双目运算符操作两个操作对象, 如 `2 + 3`. 是中置的, 因为它们出现在两个操作对象之间.
|
- 一目运算符对单一操作对象操作,如`-a`。一目运算符分前置符和后置运算符,前置运算符需紧排操作对象之前,如`!b`,后置运算符需紧跟操作对象之后,如`i++`,
|
||||||
|
- 双目运算符操作两个操作对象,如 `2 + 3`。是中置的,因为它们出现在两个操作对象之间。
|
||||||
|
- 三目运算符操作三个操作对象,和C语言一样,Swift只有一个三目运算符,就是三目条件运算符 `a?b:c`。
|
||||||
|
|
||||||
三目运算符操作三个操作对象, 和C语言一样, Swift只有一个三目运算符, 就是三目条件运算符 `a ? b : c`.
|
受运算符影响的值叫操作数,在表达式`1 + 2`中,加号`+`是双目运算符,它的两个操作数是值`1`和`2`。
|
||||||
|
|
||||||
受运算符影响的值叫操作数, 在表达式 `1 + 2` 中, 加号 `+` 是双目运算符, 它的两个操作数是值 `1` 和 `2`.
|
<a name="assignment_operator"></a>
|
||||||
|
## 赋值运算符
|
||||||
|
|
||||||
# 赋值运算符
|
赋值运算 `a = b`,表示用`b`的值来初始化或更新`a`的值。
|
||||||
|
|
||||||
赋值运算 `a = b`, 表示用 `b` 的值来初始化或更新 `a` 的值.
|
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
let b = 10
|
let b = 10
|
||||||
@ -34,12 +43,12 @@ a = b
|
|||||||
// a 现在等于 10
|
// a 现在等于 10
|
||||||
```
|
```
|
||||||
|
|
||||||
如果赋值的右边是一个多元组, 它的元素可以马上被分解多个变量或变量
|
如果赋值的右边是一个多元组,它的元素可以马上被分解多个变量或变量
|
||||||
```
|
```
|
||||||
let (x, y) = (1, 2)
|
let (x, y) = (1, 2)
|
||||||
// 现在 x 等于 1, y 等于 2
|
// 现在 x 等于 1, y 等于 2
|
||||||
```
|
```
|
||||||
与C语言和Objective-C不同, Swift的赋值操作并不返回任何值. 所以以下代码是错误的:
|
与C语言和Objective-C不同,Swift的赋值操作并不返回任何值。所以以下代码是错误的:
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
if x = y {
|
if x = y {
|
||||||
@ -47,16 +56,17 @@ if x = y {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
这个特性使得你不无法把`==`错写成`=`了, 由于`if x = y`是错误代码, Swift从底层帮你避免了这些代码错误.
|
这个特性使得你不无法把`==`错写成`=`了,由于`if x = y`是错误代码,Swift从底层帮你避免了这些代码错误。
|
||||||
|
|
||||||
# 数值运算
|
<a name="arithmetic_operators"></a>
|
||||||
|
## 数值运算
|
||||||
|
|
||||||
Swift让所有数值类型都支持了基本的四则运算:
|
Swift让所有数值类型都支持了基本的四则运算:
|
||||||
|
|
||||||
- 加法 `+`
|
- 加法`+`
|
||||||
- 减法 `-`
|
- 减法`-`
|
||||||
- 乘法 `*`
|
- 乘法`*`
|
||||||
- 除法 `/`
|
- 除法`/`
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
1 + 2 // 等于 3
|
1 + 2 // 等于 3
|
||||||
@ -65,15 +75,15 @@ Swift让所有数值类型都支持了基本的四则运算:
|
|||||||
10.0 / 2.5 // 等于 4.0
|
10.0 / 2.5 // 等于 4.0
|
||||||
```
|
```
|
||||||
|
|
||||||
与C语言和Objective-C不同的是, Swift默认不允许在数值运算中出现溢出情况. 但你可以使用Swift的溢出运算符来达到你有目的的溢出, (如 `a &+ b` ). 详情请移步: [溢出运算符](Overflow Operators).
|
与C语言和Objective-C不同的是,Swift默认不允许在数值运算中出现溢出情况。但你可以使用Swift的溢出运算符来达到你有目的的溢出,(如 `a &+ b`)。详情请移步:[溢出运算符](23_Advanced_Operators.html#overflow_operators)。
|
||||||
|
|
||||||
加法操作 `+` 也用于字符串的拼接:
|
加法操作`+`也用于字符串的拼接:
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
"hello, " + "world" // 等于 "hello, world"
|
"hello, " + "world" // 等于 "hello, world"
|
||||||
```
|
```
|
||||||
|
|
||||||
两个字符类型或一个字符类型和一个字符串类型, 相加会生成一个新的字符串类型:
|
两个字符类型或一个字符类型和一个字符串类型,相加会生成一个新的字符串类型:
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
let dog: Character = "d"
|
let dog: Character = "d"
|
||||||
@ -82,38 +92,21 @@ let dogCow = dog + cow
|
|||||||
// 译者注: 原来的引号内是很可爱的小狗和小牛, 但win os下不支持表情字符, 所以改成了普通字符
|
// 译者注: 原来的引号内是很可爱的小狗和小牛, 但win os下不支持表情字符, 所以改成了普通字符
|
||||||
// dogCow 现在是 "dc"
|
// dogCow 现在是 "dc"
|
||||||
```
|
```
|
||||||
详细请点击 [字符,字符串的拼接](http://#).
|
详细请点击[字符,字符串的拼接](03_Strings_and_Characters.html#concatenating_strings_and_characters)。
|
||||||
|
|
||||||
# 求余运算
|
### 求余运算
|
||||||
|
|
||||||
求余运算 `a % b` 是计算 `b` 的多少倍刚刚好可以容入 `a` , 多出来的那部分叫余数.
|
求余运算 `a % b` 是计算`b`的多少倍刚刚好可以容入`a`,多出来的那部分叫余数。
|
||||||
|
|
||||||
> 注意
|
>注意:
|
||||||
|
求余运算(%)在其他语言也叫取模运算。然而严格说来,我们看该运算符对负数的操作结果,"求余"比"取模"更合适些。
|
||||||
|
|
||||||
> 求余运算(%)在其他语言也叫取模运算. 然而严格说来, 我们看该运算符对负数的操作结果, `求余` 比 `取模` 更合适些.
|
我们来谈谈取余是怎么回事,计算`9 % 4`,你先计算出4的多少倍会刚好可以容入`9`中。
|
||||||
|
|
||||||
我们来谈谈取余是怎么回事, 计算 `9 % 4`, 你先计算出4的多少倍会刚好可以容入 `9` 中.
|
2倍,非常好,那余数是1(用橙色标出)
|
||||||
|
|
||||||
2倍, 非常好, 那余数是1 (用'*'标出)
|
|
||||||
|
|
||||||
<table>
|

|
||||||
<tr>
|
|
||||||
<td>1 </td>
|
|
||||||
<td>2 </td>
|
|
||||||
<td>3 </td>
|
|
||||||
<td>4 </td>
|
|
||||||
<td>5 </td>
|
|
||||||
<td>6 </td>
|
|
||||||
<td>7 </td>
|
|
||||||
<td>8 </td>
|
|
||||||
<td>9 </td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td colspan="4">4</td>
|
|
||||||
<td colspan="4">4</td>
|
|
||||||
<td>1*</td>
|
|
||||||
</tr>
|
|
||||||
</table>
|
|
||||||
|
|
||||||
在Swift中这么来表达
|
在Swift中这么来表达
|
||||||
|
|
||||||
@ -121,64 +114,66 @@ let dogCow = dog + cow
|
|||||||
9 % 4 // 等于 1
|
9 % 4 // 等于 1
|
||||||
```
|
```
|
||||||
|
|
||||||
为了得到 `a % b` 的结果, `%`计算了以下等式, 并输出`余数`作为结果:
|
为了得到 `a % b` 的结果,`%`计算了以下等式,并输出`余数`作为结果:
|
||||||
```
|
|
||||||
a = (b × 倍数) + 余数
|
|
||||||
```
|
|
||||||
当`倍数`取最大值的时候, 就会刚好可以容入 `a` 中.
|
|
||||||
|
|
||||||
把 `9` 和 `4` 代入等式中, 我们得 `1`:
|
*a = (b × 倍数) + 余数*
|
||||||
|
|
||||||
|
当`倍数`取最大值的时候,就会刚好可以容入`a`中。
|
||||||
|
|
||||||
|
把`9`和`4`代入等式中,我们得`1`:
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
9 = (4 × 2) + 1
|
9 = (4 × 2) + 1
|
||||||
```
|
```
|
||||||
|
|
||||||
同样的方法, 我来们计算 `-9 % 4` :
|
同样的方法,我来们计算 `-9 % 4`:
|
||||||
```
|
```
|
||||||
-9 % 4 // 等于 -1
|
-9 % 4 // 等于 -1
|
||||||
```
|
```
|
||||||
|
|
||||||
把 `-9` 和 `4` 代入等式, `-2` 是取到的最大整数:
|
把`-9`和`4`代入等式,`-2`是取到的最大整数:
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
-9 = (4 × -2) + -1
|
-9 = (4 × -2) + -1
|
||||||
```
|
```
|
||||||
|
|
||||||
余数是 `-1`.
|
余数是`-1`。
|
||||||
|
|
||||||
在对负数 `-b` 求余时, `-b`的符号会被忽略. 这意味着 `a % b` 和 `a % -b`的结果是相同的.
|
在对负数`-b`求余时,`-b`的符号会被忽略。这意味着 `a % b` 和 `a % -b`的结果是相同的。
|
||||||
|
|
||||||
## 浮点数求余计算
|
### 浮点数求余计算
|
||||||
|
|
||||||
不同于C和Objective-C, Swift中是可以对浮点数进行求余的.
|
不同于C和Objective-C,Swift中是可以对浮点数进行求余的。
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
8 % 2.5 // 等于 0.5
|
8 % 2.5 // 等于 0.5
|
||||||
```
|
```
|
||||||
|
|
||||||
这个例子中, 8除于2.5等于3余0.5, 所以结果是0.5.
|
这个例子中,8除于2.5等于3余0.5,所以结果是0.5。
|
||||||
|
|
||||||
# 自增和自增运算
|

|
||||||
|
|
||||||
和C一样, Swift也提供了方便对变量本身加1或减1的自增 `++` 和自减 `--` 的运算符. 其操作对象可以是整形和浮点型。
|
### 自增和自增运算
|
||||||
|
|
||||||
|
和C一样,Swift也提供了方便对变量本身加1或减1的自增`++`和自减`--`的运算符。其操作对象可以是整形和浮点型。
|
||||||
|
|
||||||
```
|
```
|
||||||
var i = 0
|
var i = 0
|
||||||
++i // 现在 i = 1
|
++i // 现在 i = 1
|
||||||
```
|
```
|
||||||
|
|
||||||
每调用一次 `++i`, `i` 的值就会加1.
|
每调用一次`++i`,`i`的值就会加1。
|
||||||
实际上, `++i` 是 `i = i + 1` 的简写, 而 `--i` 是 `i = i - 1`的简写.
|
实际上,`++i`是 `i = i + 1` 的简写,而`--i`是 `i = i - 1`的简写。
|
||||||
|
|
||||||
`++` 和 `--`既是前置又是后置运算. `++i`, `i++`, `--i` 和 `i--` 都是有效的写法.
|
`++`和`--`既是前置又是后置运算。`++i`,`i++`,`--i`和`i--`都是有效的写法。
|
||||||
|
|
||||||
我们需要注意的是这些运算符修改了 `i` 后有一个返回值. 如果你只想修改 `i` 的值, 那你就可以忽略这个返回值. 但如果你想使用返回值, 你就需要留意前置和后置操作的返回值是不同的.
|
我们需要注意的是这些运算符修改了`i`后有一个返回值。如果你只想修改`i`的值,那你就可以忽略这个返回值。但如果你想使用返回值,你就需要留意前置和后置操作的返回值是不同的。
|
||||||
|
|
||||||
当 `++` 前置的时候, 先自増再返回.
|
当`++`前置的时候,先自増再返回。
|
||||||
|
|
||||||
当 `++` 后置的时候, 先返回再自增.
|
当`++`后置的时候,先返回再自增。
|
||||||
|
|
||||||
不懂? 我们看例子:
|
不懂?我们看例子:
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
var a = 0
|
var a = 0
|
||||||
@ -186,16 +181,16 @@ let b = ++a // a 和 b 现在都是 1
|
|||||||
let c = a++ // a 现在 2, 但 c 是 a 自增前的值 1
|
let c = a++ // a 现在 2, 但 c 是 a 自增前的值 1
|
||||||
```
|
```
|
||||||
|
|
||||||
上述例子, `let b = ++a`, 先把 `a` 加1了再返回 `a` 的值. 所以 `a` 和 `b` 都是新值 `1`.
|
上述例子,`let b = ++a`,先把`a`加1了再返回`a`的值。所以`a`和`b`都是新值`1`。
|
||||||
|
|
||||||
而 `let c = a++`, 是先返回了 `a` 的值, 然后 `a` 才加1. 所以 `c` 得到了 `a` 的旧值1, 而 `a` 加1后变成2.
|
而 `let c = a++`,是先返回了`a`的值,然后`a`才加1。所以`c`得到了`a`的旧值1,而`a`加1后变成2。
|
||||||
|
|
||||||
除非你需要使用 `i++` 的特性, 不然推荐你使用 `++i` 和 `--i`, 因为先修改后返回这样的行为更符合我们的逻辑.
|
除非你需要使用`i++`的特性,不然推荐你使用`++i`和`--i`,因为先修改后返回这样的行为更符合我们的逻辑。
|
||||||
|
|
||||||
|
|
||||||
# 单目负号
|
### 单目负号
|
||||||
|
|
||||||
数值的正负号可以使用前缀 `-` (即单目负号) 来切换:
|
数值的正负号可以使用前缀`-`(即单目负号)来切换:
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
let three = 3
|
let three = 3
|
||||||
@ -203,52 +198,52 @@ let minusThree = -three // minusThree 等于 -3
|
|||||||
let plusThree = -minusThree // plusThree 等于 3, 或 "负负3"
|
let plusThree = -minusThree // plusThree 等于 3, 或 "负负3"
|
||||||
```
|
```
|
||||||
|
|
||||||
单目负号写在操作数之前, 中间没有空格.
|
单目负号写在操作数之前,中间没有空格。
|
||||||
|
|
||||||
# 单目正号
|
### 单目正号
|
||||||
|
|
||||||
单目正号 `+` 不做任何改变地返回操作数的值.
|
单目正号`+`不做任何改变地返回操作数的值。
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
let minusSix = -6
|
let minusSix = -6
|
||||||
let alsoMinusSix = +minusSix // alsoMinusSix 等于 -6
|
let alsoMinusSix = +minusSix // alsoMinusSix 等于 -6
|
||||||
```
|
```
|
||||||
虽然单目 `+` 做无用功, 但当你在使用单目负号来表达负数时, 你可以使用单目正号来表达正数, 如此你的代码会具有对称美.
|
虽然单目`+`做无用功,但当你在使用单目负号来表达负数时,你可以使用单目正号来表达正数,如此你的代码会具有对称美。
|
||||||
|
|
||||||
|
|
||||||
# 复合赋值
|
<a name="compound_assignment_operators"></a>
|
||||||
|
## 复合赋值
|
||||||
|
|
||||||
如同强大的C语言, Swift也提供把其他运算符和赋值运算 `=` 组合的复合赋值运算符, 加赋运算 `+=` 是其中一个例子:
|
如同强大的C语言,Swift也提供把其他运算符和赋值运算`=`组合的复合赋值运算符,加赋运算`+=`是其中一个例子:
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
var a = 1
|
var a = 1
|
||||||
a += 2 // a 现在是 3
|
a += 2 // a 现在是 3
|
||||||
```
|
```
|
||||||
|
|
||||||
表达式 `a += 2` 是 `a = a + 2` 的简写, 一个加赋运算就把加法和赋值两件事完成了.
|
表达式 `a += 2` 是 `a = a + 2` 的简写,一个加赋运算就把加法和赋值两件事完成了。
|
||||||
|
|
||||||
> 注意:
|
>注意:
|
||||||
|
复合赋值运算没有返回值,`let b = a += 2` 这类代码是错误。这不同于上面提到的自增和自减运算符。
|
||||||
|
|
||||||
> 复合赋值运算没有返回值, `let b = a += 2` 这类代码是错误. 这不同于上面提到的自增和自减运算符.
|
在[表达式](../chapter3/04_Expressions.html)章节里有复合运算符的完整列表。
|
||||||
|
|
||||||
[表达式](http://#)里有复合运算符的完整列表.
|
|
||||||
|
|
||||||
# 比较运算
|
<a name="comparison_operators"></a>
|
||||||
|
## 比较运算
|
||||||
|
|
||||||
所有标准C中的比较运算都可以在Swift中使用.
|
所有标准C中的比较运算都可以在Swift中使用。
|
||||||
|
|
||||||
- 等于 `a == b`
|
- 等于 `a == b`
|
||||||
- 不等于 `a != b`
|
- 不等于 `a!= b`
|
||||||
- 大于 `a > b`
|
- 大于 `a > b`
|
||||||
- 小于 `a < b`
|
- 小于 `a < b`
|
||||||
- 大于等于 `a >= b`
|
- 大于等于 `a >= b`
|
||||||
- 小于等于 `a <= b`
|
- 小于等于 `a <= b`
|
||||||
|
|
||||||
> 注意:
|
> 注意:
|
||||||
|
Swift也提供恒等`===`和不恒等`!==`这两个比较符来判断两个对象是否引用同一个对象实例。更多细节在[类与结构](09_Classes_and_Structures.html)。
|
||||||
|
|
||||||
> Swift也提供恒等 `===` 和不恒等 `!==` 这两个比较符来判断两个对象是否引用同一个对象实例. 更多细节在 [类与结构](Classes and Structures).
|
每个比较运算都返回了一个标识表达式是否成立的布尔值:
|
||||||
|
|
||||||
每个比较运算都返回了一个标识表达式是否成立的布尔值:
|
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
1 == 1 // true, 因为 1 等于 1
|
1 == 1 // true, 因为 1 等于 1
|
||||||
@ -259,7 +254,7 @@ a += 2 // a 现在是 3
|
|||||||
2 <= 1 // false, 因为 2 并不小于等于 1
|
2 <= 1 // false, 因为 2 并不小于等于 1
|
||||||
```
|
```
|
||||||
|
|
||||||
比较运算多用于条件语句, 如 `if` 条件:
|
比较运算多用于条件语句,如`if`条件:
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
let name = "world"
|
let name = "world"
|
||||||
@ -271,13 +266,14 @@ if name == "world" {
|
|||||||
// 输出 "hello, world", 因为 `name` 就是等于 "world"
|
// 输出 "hello, world", 因为 `name` 就是等于 "world"
|
||||||
```
|
```
|
||||||
|
|
||||||
关于 `if` 语句, 请看 [控制流](Control Flow).
|
关于`if`语句,请看[控制流](05_Control_Flow.html)。
|
||||||
|
|
||||||
# 三目条件运算
|
<a name="ternary_conditional_operator"></a>
|
||||||
|
## 三目条件运算
|
||||||
|
|
||||||
三目条件运算的特殊在于它是有三个操作数的运算符, 它的原型是 `问题 ? 答案1 : 答案2`. 它简洁地表达根据 `问题` 成立与否作出二选一的操作. 如果 `问题` 成立, 返回 `答案1` 的结果; 如果不成立, 返回 `答案2` 的结果.
|
三目条件运算的特殊在于它是有三个操作数的运算符,它的原型是 `问题?答案1:答案2`。它简洁地表达根据 `问题` 成立与否作出二选一的操作。如果 `问题` 成立,返回 `答案1` 的结果; 如果不成立,返回 `答案2` 的结果。
|
||||||
|
|
||||||
使用三目条件运算简化了以下代码:
|
使用三目条件运算简化了以下代码:
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
if question: {
|
if question: {
|
||||||
@ -288,7 +284,7 @@ else {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
这里有个计算表格行高的例子. 如果有表头, 那行高应比内容高度要高出50像素; 如果没有表头, 只需高出20像素.
|
这里有个计算表格行高的例子。如果有表头,那行高应比内容高度要高出50像素; 如果没有表头,只需高出20像素。
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
let contentHeight = 40
|
let contentHeight = 40
|
||||||
@ -297,7 +293,7 @@ let rowHeight = contentHeight + (hasHeader ? 50 : 20)
|
|||||||
// rowHeight 现在是 90
|
// rowHeight 现在是 90
|
||||||
```
|
```
|
||||||
|
|
||||||
这样写会比下面的代码简洁:
|
这样写会比下面的代码简洁:
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
let contentHeight = 40
|
let contentHeight = 40
|
||||||
@ -311,18 +307,19 @@ if hasHeader {
|
|||||||
// rowHeight 现在是 90
|
// rowHeight 现在是 90
|
||||||
```
|
```
|
||||||
|
|
||||||
第一段代码例子使用了三目条件运算, 所以一行代码就能让我们得到正确答案. 这比第二段代码简洁得多, 无需将 `rowHeight` 定义成变量, 因为它的值无需在 `if` 语句中改变.
|
第一段代码例子使用了三目条件运算,所以一行代码就能让我们得到正确答案。这比第二段代码简洁得多,无需将`rowHeight`定义成变量,因为它的值无需在`if`语句中改变。
|
||||||
|
|
||||||
三目条件运算提供有效率且便捷的方式来表达二选一的选择. 需要注意的事, 过度使用三目条件运算就会由简洁的代码变成难懂的代码. 我们应避免在一个组合语句使用多个三目条件运算符.
|
三目条件运算提供有效率且便捷的方式来表达二选一的选择。需要注意的事,过度使用三目条件运算就会由简洁的代码变成难懂的代码。我们应避免在一个组合语句使用多个三目条件运算符。
|
||||||
|
|
||||||
# 区间运算符
|
<a name="range_operators"></a>
|
||||||
|
## 区间运算符
|
||||||
|
|
||||||
Swift提供了两个方便表达一个区间的值的运算符.
|
Swift提供了两个方便表达一个区间的值的运算符。
|
||||||
|
|
||||||
## 闭区间运算符
|
### 闭区间运算符
|
||||||
闭区间运算符 `a...b` 定义一个包含从 `a` 到 `b` (包括 `a` 和 `b`)的所有值的区间.
|
闭区间运算符`a...b`定义一个包含从`a`到`b`(包括`a`和`b`)的所有值的区间。
|
||||||
|
|
||||||
闭区间运算符在迭代一个区间的所有值时是非常有用的, 如在 `for-in` 循环中:
|
闭区间运算符在迭代一个区间的所有值时是非常有用的,如在`for-in`循环中:
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
for index in 1...5 {
|
for index in 1...5 {
|
||||||
@ -335,14 +332,14 @@ for index in 1...5 {
|
|||||||
// 5 * 5 = 25
|
// 5 * 5 = 25
|
||||||
```
|
```
|
||||||
|
|
||||||
关于 `for-in`, 请看 [控制流](Control Flow).
|
关于`for-in`,请看[控制流](05_Control_Flow.html)。
|
||||||
|
|
||||||
## 半闭区间
|
### 半闭区间
|
||||||
|
|
||||||
半闭区间 `a..b` 定义一个从 `a` 到 `b` 但不包括 `b` 的区间.
|
半闭区间`a..b`定义一个从`a`到`b`但不包括`b`的区间。
|
||||||
之所以称为半闭区间, 是因为该区间包含第一个值而不包括最后的值.
|
之所以称为半闭区间,是因为该区间包含第一个值而不包括最后的值。
|
||||||
|
|
||||||
半闭区间的实用性在于当你使用一个0始的列表(如数组)时, 非常方便地从0数到列表的长度.
|
半闭区间的实用性在于当你使用一个0始的列表(如数组)时,非常方便地从0数到列表的长度。
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
let names = ["Anna", "Alex", "Brian", "Jack"]
|
let names = ["Anna", "Alex", "Brian", "Jack"]
|
||||||
@ -356,21 +353,23 @@ for i in 0..count {
|
|||||||
// 第 4 个人叫 Jack
|
// 第 4 个人叫 Jack
|
||||||
```
|
```
|
||||||
|
|
||||||
> 注意: 数组有4个元素, 但 `0..count` 只数到 3 (最后一个元素的下标), 因为它是半闭区间. 关于数组, 请查阅 [数组](Arrays).
|
> 注意:
|
||||||
|
数组有4个元素,但`0..count`只数到 3(最后一个元素的下标),因为它是半闭区间。关于数组,请查阅[数组](04_Collection_Types.html#arrays)。
|
||||||
|
|
||||||
# 逻辑运算
|
<a name="logical_operators"></a>
|
||||||
|
## 逻辑运算
|
||||||
|
|
||||||
逻辑运算的操作对象是逻辑布尔值. Swift支持基于C语言的三个标准逻辑运算.
|
逻辑运算的操作对象是逻辑布尔值。Swift支持基于C语言的三个标准逻辑运算。
|
||||||
|
|
||||||
- 逻辑非 `!a`
|
- 逻辑非`!a`
|
||||||
- 逻辑与 `a && b`
|
- 逻辑与 `a && b`
|
||||||
- 逻辑或 `a || b`
|
- 逻辑或 `a || b`
|
||||||
|
|
||||||
## 逻辑非
|
### 逻辑非
|
||||||
|
|
||||||
逻辑非运算 `!a` 对一个布尔值取反, 使得 `true` 变 `false`, `false` 变 `true`.
|
逻辑非运算`!a`对一个布尔值取反,使得`true`变`false`,`false`变`true`。
|
||||||
|
|
||||||
它是一个前置运算符, 需出现在操作数之前, 且不加空格. 读作 `非 a`, 然后我们看以下例子:
|
它是一个前置运算符,需出现在操作数之前,且不加空格。读作 `非 a`,然后我们看以下例子:
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
let allowedEntry = false
|
let allowedEntry = false
|
||||||
@ -380,16 +379,16 @@ if !allowedEntry {
|
|||||||
// prints "ACCESS DENIED"
|
// prints "ACCESS DENIED"
|
||||||
```
|
```
|
||||||
|
|
||||||
`if !allowedEntry`语句可以读作 "如果 非 alowed entry.", 接下一行代码只有在如果 "非 allow entry" 为 `true`, 即 `allowEntry` 为 `false` 时被执行.
|
`if!allowedEntry`语句可以读作 "如果 非 alowed entry。",接下一行代码只有在如果 "非 allow entry" 为`true`,即`allowEntry`为`false`时被执行。
|
||||||
|
|
||||||
在示例代码中, 小心地选择布尔常量或变量有助于代码的可读性, 并且避免使用双重逻辑非运算, 或混乱的逻辑语句.
|
在示例代码中,小心地选择布尔常量或变量有助于代码的可读性,并且避免使用双重逻辑非运算,或混乱的逻辑语句。
|
||||||
|
|
||||||
## 逻辑与
|
### 逻辑与
|
||||||
逻辑与 `a && b` 表达了只有 `a` 和 `b` 的值都为 `true` 时, 整个表达式的值才会是 `true` .
|
逻辑与 `a && b` 表达了只有`a`和`b`的值都为`true`时,整个表达式的值才会是`true`。
|
||||||
|
|
||||||
只要任意一个值为 `false`, 整个表达式的值就为 `false`. 事实上, 如果第一个值为 `false`, 那么是不去计算第二个值的, 因为它已经不可能影响整个表达式的结果了. 这被称做 "短路计算".
|
只要任意一个值为`false`,整个表达式的值就为`false`。事实上,如果第一个值为`false`,那么是不去计算第二个值的,因为它已经不可能影响整个表达式的结果了。这被称做 "短路计算"。
|
||||||
|
|
||||||
以下例子, 只有两个值都为值的时候才允许进入:
|
以下例子,只有两个值都为值的时候才允许进入:
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
let enteredDoorCode = true
|
let enteredDoorCode = true
|
||||||
@ -402,12 +401,12 @@ if enteredDoorCode && passedRetinaScan {
|
|||||||
// 输出 "ACCESS DENIED
|
// 输出 "ACCESS DENIED
|
||||||
```
|
```
|
||||||
|
|
||||||
## 逻辑或
|
### 逻辑或
|
||||||
逻辑或 `a || b` 是一个由两个连续的 `|` 组成的中置运算符. 它表示了两个逻辑表达式的其中一个为 `true`, 整个表达式就为 `true`.
|
逻辑或 `a || b` 是一个由两个连续的`|`组成的中置运算符。它表示了两个逻辑表达式的其中一个为`true`,整个表达式就为`true`。
|
||||||
|
|
||||||
同逻辑与运算类似, 逻辑或也是"短路计算"的, 当左端的表达式为 `true` 时, 将不计算右边的表达式了, 因为它不可能改变整个表达式的值了.
|
同逻辑与运算类似,逻辑或也是"短路计算"的,当左端的表达式为`true`时,将不计算右边的表达式了,因为它不可能改变整个表达式的值了。
|
||||||
|
|
||||||
以下示例代码中, 第一个布尔值 `hasDoorKey` 为 `false`, 但第二个值 `knowsOverridePassword` 为 `true`, 所以整个表达是 `true`, 于是允许进入:
|
以下示例代码中,第一个布尔值`hasDoorKey`为`false`,但第二个值`knowsOverridePassword`为`true`,所以整个表达是`true`,于是允许进入:
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
let hasDoorKey = false
|
let hasDoorKey = false
|
||||||
@ -420,9 +419,9 @@ if hasDoorKey || knowsOverridePassword {
|
|||||||
// 输出 "Welcome!"
|
// 输出 "Welcome!"
|
||||||
```
|
```
|
||||||
|
|
||||||
## 组合逻辑
|
### 组合逻辑
|
||||||
|
|
||||||
我们可以组合多个逻辑运算来表达一个复合逻辑:
|
我们可以组合多个逻辑运算来表达一个复合逻辑:
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
if enteredDoorCode && passedRetinaScan || hasDoorKey || knowsOverridePassword {
|
if enteredDoorCode && passedRetinaScan || hasDoorKey || knowsOverridePassword {
|
||||||
@ -433,15 +432,15 @@ if enteredDoorCode && passedRetinaScan || hasDoorKey || knowsOverridePassword {
|
|||||||
// 输出 "Welcome!"
|
// 输出 "Welcome!"
|
||||||
```
|
```
|
||||||
|
|
||||||
这个例子使用了含多个 `&&` 和 `||` 的复合逻辑. 但无论怎样, `&&` 和 `||` 始终只能操作两个值. 所以这实际是三个简单逻辑连续操作的结果. 我们来解读一下:
|
这个例子使用了含多个`&&`和`||`的复合逻辑。但无论怎样,`&&`和`||`始终只能操作两个值。所以这实际是三个简单逻辑连续操作的结果。我们来解读一下:
|
||||||
|
|
||||||
如果我们输入了正确的密码并通过了视网膜扫描; 或者我们有一把有效的钥匙; 又或者我们知道紧急情况下重置的密码, 我们就能把门打开进入.
|
如果我们输入了正确的密码并通过了视网膜扫描; 或者我们有一把有效的钥匙; 又或者我们知道紧急情况下重置的密码,我们就能把门打开进入。
|
||||||
|
|
||||||
前两种情况, 我们都不满足, 所以前两个简单逻辑的结果是 `false`, 但是我们是知道紧急情况下重置的密码的, 所以整个复杂表达式的值还是 `true`.
|
前两种情况,我们都不满足,所以前两个简单逻辑的结果是`false`,但是我们是知道紧急情况下重置的密码的,所以整个复杂表达式的值还是`true`。
|
||||||
|
|
||||||
## 使用括号来明确优先级
|
### 使用括号来明确优先级
|
||||||
|
|
||||||
为了一个复杂表达式更容易读懂, 在合适的地方使用括号来明确优先级是很有效的, 虽然它并非必要的. 在上个关于门的权限的例子中, 我们给第一个部分加个括号, 使用它看起来逻辑更明确.
|
为了一个复杂表达式更容易读懂,在合适的地方使用括号来明确优先级是很有效的,虽然它并非必要的。在上个关于门的权限的例子中,我们给第一个部分加个括号,使用它看起来逻辑更明确。
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
if (enteredDoorCode && passedRetinaScan) || hasDoorKey || knowsOverridePassword {
|
if (enteredDoorCode && passedRetinaScan) || hasDoorKey || knowsOverridePassword {
|
||||||
@ -452,6 +451,6 @@ if (enteredDoorCode && passedRetinaScan) || hasDoorKey || knowsOverridePassword
|
|||||||
// prints "Welcome!"
|
// prints "Welcome!"
|
||||||
```
|
```
|
||||||
|
|
||||||
这括号使得前两个值被看成整个逻辑表达中独立的一个部分. 虽然有括号和没括号的输出结果是一样的, 但对于读代码的人来说有括号的代码更清晰.
|
这括号使得前两个值被看成整个逻辑表达中独立的一个部分。虽然有括号和没括号的输出结果是一样的,但对于读代码的人来说有括号的代码更清晰。
|
||||||
|
|
||||||
可读性比简洁性更重要, 请在可以让你代码变清晰地地方加个括号吧!
|
可读性比简洁性更重要,请在可以让你代码变清晰地地方加个括号吧!
|
||||||
|
|||||||
@ -1,44 +1,56 @@
|
|||||||
|
# 高级运算符
|
||||||
|
-----------------
|
||||||
|
|
||||||
|
本页内容包括:
|
||||||
|
|
||||||
|
- [位运算符](#bitwise_operators)
|
||||||
|
- [溢出运算符](#overflow_operators)
|
||||||
|
- [优先级和结合性(Precedence and Associativity)](#precedence_and_associativity)
|
||||||
|
- [运算符函数(Operator Functions)](#operator_functions)
|
||||||
|
- [自定义运算符](#custom_operators)
|
||||||
|
|
||||||
In addition to the operators described in [Basic Operators](Basic Operators), Swift provides several advanced operators that perform more complex value manipulation. These include all of the bitwise and bit shifting operators you will be familiar with from C and Objective-C.
|
In addition to the operators described in [Basic Operators](Basic Operators), Swift provides several advanced operators that perform more complex value manipulation. These include all of the bitwise and bit shifting operators you will be familiar with from C and Objective-C.
|
||||||
|
|
||||||
除于[基本操作符](Basic Operators)中所讲的运算符, Swift还有许多复杂的高级运算符, 包括了C语和Objective-C中的位运算符和位移运算.
|
除了[基本操作符](02_Basic_Operators.html)中所讲的运算符,Swift还有许多复杂的高级运算符,包括了C语和Objective-C中的位运算符和移位运算。
|
||||||
|
|
||||||
Unlike arithmetic operators in C, arithmetic operators in Swift do not overflow by default. Overflow behavior is trapped and reported as an error. To opt in to overflow behavior, use Swift’s second set of arithmetic operators that overflow by default, such as the overflow addition operator (&+). All of these overflow operators begin with an ampersand (&).
|
Unlike arithmetic operators in C, arithmetic operators in Swift do not overflow by default. Overflow behavior is trapped and reported as an error. To opt in to overflow behavior, use Swift’s second set of arithmetic operators that overflow by default, such as the overflow addition operator (&+). All of these overflow operators begin with an ampersand (&).
|
||||||
|
|
||||||
不同于C语言中的数值计算, Swift的数值计算默认是不可溢出的. 溢出行为会被捕获并报告为错误. 你是故意的? 好吧, 你可以使用Swift为你准备的另一套默认允许溢出的数值运算符, 如可溢出加 `&+`. 所有允许溢出的运算符都是以 `&` 开始的.
|
不同于C语言中的数值计算,Swift的数值计算默认是不可溢出的。溢出行为会被捕获并报告为错误。你是故意的?好吧,你可以使用Swift为你准备的另一套默认允许溢出的数值运算符,如可溢出加`&+`。所有允许溢出的运算符都是以`&`开始的。
|
||||||
|
|
||||||
When you define your own structures, classes, and enumerations, it can be useful to provide your own implementations of the standard Swift operators for these custom types. Swift makes it easy to provide tailored implementations of these operators and to determine exactly what their behavior should be for each type you create.
|
When you define your own structures, classes, and enumerations, it can be useful to provide your own implementations of the standard Swift operators for these custom types. Swift makes it easy to provide tailored implementations of these operators and to determine exactly what their behavior should be for each type you create.
|
||||||
|
|
||||||
自定义的结构, 类和枚举, 是否可以使用标准的运算符来定义操作? 当然可以, 在Swift中, 你可以对你创建的类型定制运算符的行为.
|
自定义的结构,类和枚举,是否可以使用标准的运算符来定义操作?当然可以!在Swift中,你可以为你创建的所有类型定制运算符的操作。
|
||||||
|
|
||||||
You’re not just limited to the predefined operators. Swift gives you the freedom to define your own custom infix, prefix, postfix, and assignment operators, with custom precedence and associativity values. These operators can be used and adopted in your code just like any of the predefined operators, and you can even extend existing types to support the custom operators you define.
|
You’re not just limited to the predefined operators. Swift gives you the freedom to define your own custom infix, prefix, postfix, and assignment operators, with custom precedence and associativity values. These operators can be used and adopted in your code just like any of the predefined operators, and you can even extend existing types to support the custom operators you define.
|
||||||
|
|
||||||
可定制的运算符并不限于那些预设的运算符, 也创建个性的中置, 前置,后置,还有赋值运算符, 当然优先级和结合性也是可以自定义的. 这些运算符的实现可以使用预设的运算符, 也可以使用已定制好的运算符.
|
可定制的运算符并不限于那些预设的运算符,自定义有个性的中置,前置,后置及赋值运算符,当然还有优先级和结合性。这些运算符的实现可以运用预设的运算符,也可以运用之前定制的运算符。
|
||||||
|
|
||||||
# Bitwise Operators
|
## Bitwise Operators
|
||||||
|
|
||||||
# 位运算符
|
<a name="bitwise_operators"></a>
|
||||||
|
## 位运算符
|
||||||
|
|
||||||
Bitwise operators enable you to manipulate the individual raw data bits within a data structure. They are often used in low-level programming, such as graphics programming and device driver creation. Bitwise operators can also be useful when you work with raw data from external sources, such as encoding and decoding data for communication over a custom protocol.
|
Bitwise operators enable you to manipulate the individual raw data bits within a data structure. They are often used in low-level programming, such as graphics programming and device driver creation. Bitwise operators can also be useful when you work with raw data from external sources, such as encoding and decoding data for communication over a custom protocol.
|
||||||
|
|
||||||
位操作符通常在诸如图像处理和创建设备驱动等底层开发中使用, 使用它可以操作数据结构中原始数据中的个别比特. 当然, 使用一个自定的协议进行通信的时候, 使用位运算符来对原始数据进行编码和解码也是非常有效的.
|
位操作符通常在诸如图像处理和创建设备驱动等底层开发中使用,使用它可以单独操作数据结构中原始数据的比特位。在使用一个自定义的协议进行通信的时候,运用位运算符来对原始数据进行编码和解码也是非常有效的。
|
||||||
|
|
||||||
Swift supports all of the bitwise operators found in C, as described below.
|
Swift supports all of the bitwise operators found in C, as described below.
|
||||||
|
|
||||||
Swift支持所有C语言的位运算符, 如下描述:
|
Swift支持如下所有C语言的位运算符:
|
||||||
|
|
||||||
## Bitwise NOT Operator
|
### Bitwise NOT Operator
|
||||||
|
|
||||||
## 按位取反运算符
|
### 按位取反运算符
|
||||||
|
|
||||||
The bitwise NOT operator (~) inverts all bits in a number:
|
The bitwise NOT operator (~) inverts all bits in a number:
|
||||||
|
|
||||||
按位取反运算符 `~` 对一个操作数的每一位都取反.
|
按位取反运算符`~`对一个操作数的每一位都取反。
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
The bitwise NOT operator is a prefix operator, and appears immediately before the value it operates on, without any white space:
|
The bitwise NOT operator is a prefix operator, and appears immediately before the value it operates on, without any white space:
|
||||||
|
|
||||||
这个运算符是前置, 所以请不加任何空格地写着操作数之前.
|
这个运算符是前置的,所以请不加任何空格地写着操作数之前。
|
||||||
|
|
||||||
```
|
```
|
||||||
let initialBits: UInt8 = 0b00001111
|
let initialBits: UInt8 = 0b00001111
|
||||||
@ -47,25 +59,25 @@ let invertedBits = ~initialBits // 等于 0b11110000
|
|||||||
|
|
||||||
UInt8 integers have eight bits and can store any value between 0 and 255. This example initializes a UInt8 integer with the binary value 00001111, which has its first four bits set to 0, and its second four bits set to 1. This is equivalent to a decimal value of 15.
|
UInt8 integers have eight bits and can store any value between 0 and 255. This example initializes a UInt8 integer with the binary value 00001111, which has its first four bits set to 0, and its second four bits set to 1. This is equivalent to a decimal value of 15.
|
||||||
|
|
||||||
`UInt8` 整型是8位的, 可以储存0~255之间的任意数. 这个例子初始化一个整型为二进制值 `00001111`(前4位为 `0`, 后4位为 `1`), 它的十进制值为 `15`.
|
`UInt8`是8位无符整型,可以存储0~255之间的任意数。这个例子初始化一个整型为二进制值`00001111`(前4位为`0`,后4位为`1`),它的十进制值为`15`。
|
||||||
|
|
||||||
The bitwise NOT operator is then used to create a new constant called invertedBits, which is equal to initialBits, but with all of the bits inverted. Zeroes become ones, and ones become zeroes. The value of invertedBits is 11110000, which is equal to an unsigned decimal value of 240.
|
The bitwise NOT operator is then used to create a new constant called invertedBits, which is equal to initialBits, but with all of the bits inverted. Zeroes become ones, and ones become zeroes. The value of invertedBits is 11110000, which is equal to an unsigned decimal value of 240.
|
||||||
|
|
||||||
使用按位取反运算 `~` 对 `initialBits` 操作, 然后赋值给 `invertedBits` 这个新常量. 这个新常量的值等于所有位都取反的`initialBits`, 即 `1` 变成 `0`, `0` 变成 `1`, 变成了 `11110000`, 十进制值为 `240`.
|
使用按位取反运算`~`对`initialBits`操作,然后赋值给`invertedBits`这个新常量。这个新常量的值等于所有位都取反的`initialBits`,即`1`变成`0`,`0`变成`1`,变成了`11110000`,十进制值为`240`。
|
||||||
|
|
||||||
## Bitwise AND Operator
|
### Bitwise AND Operator
|
||||||
|
|
||||||
## 按位与运算符
|
### 按位与运算符
|
||||||
|
|
||||||
The bitwise AND operator (&) combines the bits of two numbers. It returns a new number whose bits are set to 1 only if the bits were equal to 1 in both input numbers:
|
The bitwise AND operator (&) combines the bits of two numbers. It returns a new number whose bits are set to 1 only if the bits were equal to 1 in both input numbers:
|
||||||
|
|
||||||
按位与运算符对两个数进行操作, 然后返回一个新的数, 这个数的每个位都需两个输入数的同一位都为1的时候才为1.
|
按位与运算符对两个数进行操作,然后返回一个新的数,这个数的每个位都需要两个输入数的同一位都为1时才为1。
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
In the example below, the values of firstSixBits and lastSixBits both have four middle bits equal to 1. The bitwise AND operator combines them to make the number 00111100, which is equal to an unsigned decimal value of 60:
|
In the example below, the values of firstSixBits and lastSixBits both have four middle bits equal to 1. The bitwise AND operator combines them to make the number 00111100, which is equal to an unsigned decimal value of 60:
|
||||||
|
|
||||||
如下代码, `firstSixBits` 和 `lastSixBits` 中间4个位都为1. 对它俩进行按位与运算后, 就得到了 `00111100`, 即十进制的 `60`.
|
以下代码,`firstSixBits`和`lastSixBits`中间4个位都为1。对它俩进行按位与运算后,就得到了`00111100`,即十进制的`60`。
|
||||||
|
|
||||||
```
|
```
|
||||||
let firstSixBits: UInt8 = 0b11111100
|
let firstSixBits: UInt8 = 0b11111100
|
||||||
@ -73,19 +85,19 @@ let lastSixBits: UInt8 = 0b00111111
|
|||||||
let middleFourBits = firstSixBits & lastSixBits // 等于 00111100
|
let middleFourBits = firstSixBits & lastSixBits // 等于 00111100
|
||||||
```
|
```
|
||||||
|
|
||||||
## Bitwise OR Operator
|
### Bitwise OR Operator
|
||||||
|
|
||||||
## 按位或运算
|
### 按位或运算
|
||||||
|
|
||||||
The bitwise OR operator (|) compares the bits of two numbers. The operator returns a new number whose bits are set to 1 if the bits are equal to 1 in either input number:
|
The bitwise OR operator (|) compares the bits of two numbers. The operator returns a new number whose bits are set to 1 if the bits are equal to 1 in either input number:
|
||||||
|
|
||||||
按位或运算符 `|` 比较两个数, 然后返回一个新的数, 这个数的每一位设置1的条件是两个输入数的同一位都不为0(即任意一个为1, 或都为1).
|
按位或运算符`|`比较两个数,然后返回一个新的数,这个数的每一位设置1的条件是两个输入数的同一位都不为0(即任意一个为1,或都为1)。
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
In the example below, the values of someBits and moreBits have different bits set to 1. The bitwise OR operator combines them to make the number 11111110, which equals an unsigned decimal of 254:
|
In the example below, the values of someBits and moreBits have different bits set to 1. The bitwise OR operator combines them to make the number 11111110, which equals an unsigned decimal of 254:
|
||||||
|
|
||||||
如下代码, `someBits` 和 `moreBits` 在不同位上有 `1`. 按位或运行的结果是 `11111110`, 即十进制的 `254`.
|
如下代码,`someBits`和`moreBits`在不同位上有`1`。按位或运行的结果是`11111110`,即十进制的`254`。
|
||||||
|
|
||||||
```
|
```
|
||||||
let someBits: UInt8 = 0b10110010
|
let someBits: UInt8 = 0b10110010
|
||||||
@ -93,19 +105,19 @@ let moreBits: UInt8 = 0b01011110
|
|||||||
let combinedbits = someBits | moreBits // 等于 11111110
|
let combinedbits = someBits | moreBits // 等于 11111110
|
||||||
```
|
```
|
||||||
|
|
||||||
## Bitwise XOR Operator
|
### Bitwise XOR Operator
|
||||||
|
|
||||||
## 按位异或运算符
|
### 按位异或运算符
|
||||||
|
|
||||||
The bitwise XOR operator, or “exclusive OR operator” (^), compares the bits of two numbers. The operator returns a new number whose bits are set to 1 where the input bits are different and are set to 0 where the input bits are the same:
|
The bitwise XOR operator, or “exclusive OR operator” (^), compares the bits of two numbers. The operator returns a new number whose bits are set to 1 where the input bits are different and are set to 0 where the input bits are the same:
|
||||||
|
|
||||||
按位异或运算符 `^` 比较两个数, 然后返回一个数, 这个数的每个位设为 `1`的条件是两个输入数的同一位不同, 如果相同就设为 `0`.
|
按位异或运算符`^`比较两个数,然后返回一个数,这个数的每个位设为`1`的条件是两个输入数的同一位不同,如果相同就设为`0`。
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
In the example below, the values of firstBits and otherBits each have a bit set to 1 in a location that the other does not. The bitwise XOR operator sets both of these bits to 1 in its output value. All of the other bits in firstBits and otherBits match and are set to 0 in the output value:
|
In the example below, the values of firstBits and otherBits each have a bit set to 1 in a location that the other does not. The bitwise XOR operator sets both of these bits to 1 in its output value. All of the other bits in firstBits and otherBits match and are set to 0 in the output value:
|
||||||
|
|
||||||
以下代码, `firstBits` 和 `otherBits` 都有一个 `1` 跟另一个数不同的. 所以按位异或的结果是把它这些位置为 `1`, 其他都置为 `0`.
|
以下代码,`firstBits`和`otherBits`都有一个`1`跟另一个数不同的。所以按位异或的结果是把它这些位置为`1`,其他都置为`0`。
|
||||||
|
|
||||||
```
|
```
|
||||||
let firstBits: UInt8 = 0b00010100
|
let firstBits: UInt8 = 0b00010100
|
||||||
@ -113,33 +125,33 @@ let otherBits: UInt8 = 0b00000101
|
|||||||
let outputBits = firstBits ^ otherBits // 等于 00010001
|
let outputBits = firstBits ^ otherBits // 等于 00010001
|
||||||
```
|
```
|
||||||
|
|
||||||
## Bitwise Left and Right Shift Operators
|
### Bitwise Left and Right Shift Operators
|
||||||
## 按位左移/右移运算符
|
### 按位左移/右移运算符
|
||||||
|
|
||||||
The bitwise left shift operator (<<) and bitwise right shift operator (>>) move all bits in a number to the left or the right by a certain number of places, according to the rules defined below.
|
The bitwise left shift operator (<<) and bitwise right shift operator (>>) move all bits in a number to the left or the right by a certain number of places, according to the rules defined below.
|
||||||
|
|
||||||
左移运算符 `<<` 和右移运算符 `>>` 会把一个数的所有比特位按以下定义的规则向左或向右移动指定位数.
|
左移运算符`<<`和右移运算符`>>`会把一个数的所有比特位按以下定义的规则向左或向右移动指定位数。
|
||||||
|
|
||||||
Bitwise left and right shifts have the effect of multiplying or dividing an integer number by a factor of two. Shifting an integer’s bits to the left by one position doubles its value, whereas shifting it to the right by one position halves its value.
|
Bitwise left and right shifts have the effect of multiplying or dividing an integer number by a factor of two. Shifting an integer’s bits to the left by one position doubles its value, whereas shifting it to the right by one position halves its value.
|
||||||
|
|
||||||
按位左移和按位右移的效果相当把一个整数乘于或除于一个因子为 `2` 的整数. 向左移动一个整型的比特位相当于把这个数乘于 `2`, 向右移一位就是除于 `2`.
|
按位左移和按位右移的效果相当把一个整数乘于或除于一个因子为`2`的整数。向左移动一个整型的比特位相当于把这个数乘于`2`,向右移一位就是除于`2`。
|
||||||
|
|
||||||
### Shifting Behavior for Unsigned Integers
|
#### Shifting Behavior for Unsigned Integers
|
||||||
### 对无符整型进行移位
|
#### 无符整型的移位操作
|
||||||
|
|
||||||
The bit-shifting behavior for unsigned integers is as follows:
|
The bit-shifting behavior for unsigned integers is as follows:
|
||||||
对无符整型的移位的效果如下:
|
对无符整型的移位的效果如下:
|
||||||
|
|
||||||
Existing bits are moved to the left or right by the requested number of places.
|
Existing bits are moved to the left or right by the requested number of places.
|
||||||
Any bits that are moved beyond the bounds of the integer’s storage are discarded.
|
Any bits that are moved beyond the bounds of the integer’s storage are discarded.
|
||||||
Zeroes are inserted in the spaces left behind after the original bits are moved to the left or right.
|
Zeroes are inserted in the spaces left behind after the original bits are moved to the left or right.
|
||||||
This approach is known as a logical shift.
|
This approach is known as a logical shift.
|
||||||
|
|
||||||
已经存在的比特位向左或向右移动指定的位数. 被移出整型存储边界的的位数直接抛弃, 移动留下的空白位用零 `0` 来填充. 这种方法称为逻辑移位.
|
已经存在的比特位向左或向右移动指定的位数。被移出整型存储边界的的位数直接抛弃,移动留下的空白位用零`0`来填充。这种方法称为逻辑移位。
|
||||||
|
|
||||||
The illustration below shows the results of 11111111 << 1 (which is 11111111 shifted to the left by 1 place), and 11111111 >> 1 (which is 11111111 shifted to the right by 1 place). Blue numbers are shifted, gray numbers are discarded, and orange zeroes are inserted:
|
The illustration below shows the results of 11111111 << 1 (which is 11111111 shifted to the left by 1 place), and 11111111 >> 1 (which is 11111111 shifted to the right by 1 place). Blue numbers are shifted, gray numbers are discarded, and orange zeroes are inserted:
|
||||||
|
|
||||||
以下这张把展示了 `11111111 << 1` (`11111111` 向左移1位), 和 `11111111 << 1` (`11111111` 向右移1位). 蓝色的是被移位的, 灰色是被抛弃的, 橙色的 `0` 是被填充进来的.
|
以下这张把展示了 `11111111 << 1`(`11111111`向左移1位),和 `11111111 >> 1`(`11111111`向右移1位)。蓝色的是被移位的,灰色是被抛弃的,橙色的`0`是被填充进来的。
|
||||||
|
|
||||||

|

|
||||||
Here’s how bit shifting looks in Swift code:
|
Here’s how bit shifting looks in Swift code:
|
||||||
@ -154,7 +166,7 @@ shiftBits >> 2 // 00000001
|
|||||||
```
|
```
|
||||||
|
|
||||||
You can use bit shifting to encode and decode values within other data types:
|
You can use bit shifting to encode and decode values within other data types:
|
||||||
你可以使用移位操作进行其他数据类型的编码和解码.
|
你可以使用移位操作进行其他数据类型的编码和解码。
|
||||||
|
|
||||||
```
|
```
|
||||||
let pink: UInt32 = 0xCC6699
|
let pink: UInt32 = 0xCC6699
|
||||||
@ -165,127 +177,192 @@ let blueComponent = pink & 0x0000FF // blueComponent 是 0x99, 即 153
|
|||||||
|
|
||||||
This example uses a UInt32 constant called pink to store a Cascading Style Sheets color value for the color pink. The CSS color value #CC6699 is written as 0xCC6699 in Swift’s hexadecimal number representation. This color is then decomposed into its red (CC), green (66), and blue (99) components by the bitwise AND operator (&) and the bitwise right shift operator (>>).
|
This example uses a UInt32 constant called pink to store a Cascading Style Sheets color value for the color pink. The CSS color value #CC6699 is written as 0xCC6699 in Swift’s hexadecimal number representation. This color is then decomposed into its red (CC), green (66), and blue (99) components by the bitwise AND operator (&) and the bitwise right shift operator (>>).
|
||||||
|
|
||||||
这个例子使用了一个 `UInt32` 的命名为 `pink`的常量来储存层叠样式表 `CSS` 中粉色的颜色值, `CSS`颜色`#CC6699`在Swift用十六进制`0xCC6699`来表示. 然后使用按位与(&)和按位右移就可以从这个颜色值中解析出红(CC), 绿(66), 蓝(99)三个部分.
|
这个例子使用了一个`UInt32`的命名为`pink`的常量来存储层叠样式表`CSS`中粉色的颜色值,`CSS`颜色`#CC6699`在Swift用十六进制`0xCC6699`来表示。然后使用按位与(&)和按位右移就可以从这个颜色值中解析出红(CC),绿(66),蓝(99)三个部分。
|
||||||
|
|
||||||
The red component is obtained by performing a bitwise AND between the numbers 0xCC6699 and 0xFF0000. The zeroes in 0xFF0000 effectively “mask” the second and third bytes of 0xCC6699, causing the 6699 to be ignored and leaving 0xCC0000 as the result.
|
The red component is obtained by performing a bitwise AND between the numbers 0xCC6699 and 0xFF0000. The zeroes in 0xFF0000 effectively “mask” the second and third bytes of 0xCC6699, causing the 6699 to be ignored and leaving 0xCC0000 as the result.
|
||||||
|
|
||||||
对 `0xCC6699` 和 `0xFF0000` 进行按位与 `&` 操作就可以得到红色部分. `0xFF0000` 中的 `0` 了遮盖了 `OxCC6699` 的第二和第三个字节, 这样 `6699` 被忽略了, 只留下 `0xCC0000`.
|
对`0xCC6699`和`0xFF0000`进行按位与`&`操作就可以得到红色部分。`0xFF0000`中的`0`了遮盖了`OxCC6699`的第二和第三个字节,这样`6699`被忽略了,只留下`0xCC0000`。
|
||||||
|
|
||||||
This number is then shifted 16 places to the right (>> 16). Each pair of characters in a hexadecimal number uses 8 bits, so a move 16 places to the right will convert 0xCC0000 into 0x0000CC. This is the same as 0xCC, which has a decimal value of 204.
|
This number is then shifted 16 places to the right (>> 16). Each pair of characters in a hexadecimal number uses 8 bits, so a move 16 places to the right will convert 0xCC0000 into 0x0000CC. This is the same as 0xCC, which has a decimal value of 204.
|
||||||
|
|
||||||
然后, 按向右移动16位, 即 `>> 16`. 十六进制中每两个字符是8比特位, 所以移动16位的结果是把 `0xCC0000` 变成 `0x0000CC`. 这和 `0xCC` 是相等的, 都是十进制的 `204`.
|
然后,按向右移动16位,即 `>> 16`。十六进制中每两个字符是8比特位,所以移动16位的结果是把`0xCC0000`变成`0x0000CC`。这和`0xCC`是相等的,都是十进制的`204`。
|
||||||
|
|
||||||
Similarly, the green component is obtained by performing a bitwise AND between the numbers 0xCC6699 and 0x00FF00, which gives an output value of 0x006600. This output value is then shifted eight places to the right, giving a a value of 0x66, which has a decimal value of 102.
|
Similarly, the green component is obtained by performing a bitwise AND between the numbers 0xCC6699 and 0x00FF00, which gives an output value of 0x006600. This output value is then shifted eight places to the right, giving a a value of 0x66, which has a decimal value of 102.
|
||||||
|
|
||||||
同样的, 绿色部分来自于 `0xCC6699` 和 `0x00FF00` 的按位操作得到 `0x006600`. 然后向右移动8們, 得到 `0x66`, 即十进制的 `102`.
|
同样的,绿色部分来自于`0xCC6699`和`0x00FF00`的按位操作得到`0x006600`。然后向右移动8們,得到`0x66`,即十进制的`102`。
|
||||||
|
|
||||||
Finally, the blue component is obtained by performing a bitwise AND between the numbers 0xCC6699 and 0x0000FF, which gives an output value of 0x000099. There’s no need to shift this to the right, as 0x000099 already equals 0x99, which has a decimal value of 153.
|
Finally, the blue component is obtained by performing a bitwise AND between the numbers 0xCC6699 and 0x0000FF, which gives an output value of 0x000099. There’s no need to shift this to the right, as 0x000099 already equals 0x99, which has a decimal value of 153.
|
||||||
|
|
||||||
最后, 蓝色部分对 `0xCC6699` 和 `0x0000FF` 进行按位与运算, 得到 `0x000099`, 无需向右移位了, 所以结果就是 `0x99`, 即十进制的 `153`.
|
最后,蓝色部分对`0xCC6699`和`0x0000FF`进行按位与运算,得到`0x000099`,无需向右移位了,所以结果就是`0x99`,即十进制的`153`。
|
||||||
|
|
||||||
### Shifting Behavior for Signed Integers
|
#### Shifting Behavior for Signed Integers
|
||||||
|
#### 有符整型的移位操作
|
||||||
|
|
||||||
The shifting behavior is more complex for signed integers than for unsigned integers, because of the way signed integers are represented in binary. (The examples below are based on 8-bit signed integers for simplicity, but the same principles apply for signed integers of any size.)
|
The shifting behavior is more complex for signed integers than for unsigned integers, because of the way signed integers are represented in binary. (The examples below are based on 8-bit signed integers for simplicity, but the same principles apply for signed integers of any size.)
|
||||||
|
|
||||||
|
有符整型的移位操作相对复杂得多,因为正负号也是用二进制位表示的。(这里举的例子虽然都是8位的,但它的原理是通用的。)
|
||||||
|
|
||||||
Signed integers use their first bit (known as the sign bit) to indicate whether the integer is positive or negative. A sign bit of 0 means positive, and a sign bit of 1 means negative.
|
Signed integers use their first bit (known as the sign bit) to indicate whether the integer is positive or negative. A sign bit of 0 means positive, and a sign bit of 1 means negative.
|
||||||
|
|
||||||
|
有符整型通过第1个比特位(称为符号位)来表达这个整数是正数还是负数。`0`代表正数,`1`代表负数。
|
||||||
|
|
||||||
The remaining bits (known as the value bits) store the actual value. Positive numbers are stored in exactly the same way as for unsigned integers, counting upwards from 0. Here’s how the bits inside an Int8 look for the number 4:
|
The remaining bits (known as the value bits) store the actual value. Positive numbers are stored in exactly the same way as for unsigned integers, counting upwards from 0. Here’s how the bits inside an Int8 look for the number 4:
|
||||||
|
|
||||||
|
其余的比特位(称为数值位)存储其实值。有符正整数和无符正整数在计算机里的存储结果是一样的,下来我们来看`+4`内部的二进制结构。
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
The sign bit is 0 (meaning “positive”), and the seven value bits are just the number 4, written in binary notation.
|
The sign bit is 0 (meaning “positive”), and the seven value bits are just the number 4, written in binary notation.
|
||||||
|
|
||||||
|
符号位为`0`,代表正数,另外7比特位二进制表示的实际值就刚好是`4`。
|
||||||
|
|
||||||
Negative numbers, however, are stored differently. They are stored by subtracting their absolute value from 2 to the power of n, where n is the number of value bits. An eight-bit number has seven value bits, so this means 2 to the power of 7, or 128.
|
Negative numbers, however, are stored differently. They are stored by subtracting their absolute value from 2 to the power of n, where n is the number of value bits. An eight-bit number has seven value bits, so this means 2 to the power of 7, or 128.
|
||||||
|
|
||||||
|
负数呢,跟正数不同。负数存储的是2的n次方减去它的绝对值,n为数值位的位数。一个8比特的数有7个数值位,所以是2的7次方,即128。
|
||||||
|
|
||||||
Here’s how the bits inside an Int8 look for the number -4:
|
Here’s how the bits inside an Int8 look for the number -4:
|
||||||
|
|
||||||
|
我们来看`-4`存储的二进制结构。
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
This time, the sign bit is 1 (meaning “negative”), and the seven value bits have a binary value of 124 (which is 128 - 4):
|
This time, the sign bit is 1 (meaning “negative”), and the seven value bits have a binary value of 124 (which is 128 - 4):
|
||||||
|
|
||||||
|
现在符号位为`1`,代表负数,7个数值位要表达的二进制值是124,即128 - 4。
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
The encoding for negative numbers is known as a two’s complement representation. It may seem an unusual way to represent negative numbers, but it has several advantages.
|
The encoding for negative numbers is known as a two’s complement representation. It may seem an unusual way to represent negative numbers, but it has several advantages.
|
||||||
|
|
||||||
|
负数的编码方式称为二进制补码表示。这种表示方式看起来很奇怪,但它有几个优点。
|
||||||
|
|
||||||
First, you can add -1 to -4, simply by performing a standard binary addition of all eight bits (including the sign bit), and discarding anything that doesn’t fit in the eight bits once you’re done:
|
First, you can add -1 to -4, simply by performing a standard binary addition of all eight bits (including the sign bit), and discarding anything that doesn’t fit in the eight bits once you’re done:
|
||||||
|
|
||||||
|
首先,只需要对全部8个比特位(包括符号)做标准的二进制加法就可以完成 `-1 + -4` 的操作,忽略加法过程产生的超过8个比特位表达的任何信息。
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
Second, the two’s complement representation also lets you shift the bits of negative numbers to the left and right like positive numbers, and still end up doubling them for every shift you make to the left, or halving them for every shift you make to the right. To achieve this, an extra rule is used when signed integers are shifted to the right:
|
Second, the two’s complement representation also lets you shift the bits of negative numbers to the left and right like positive numbers, and still end up doubling them for every shift you make to the left, or halving them for every shift you make to the right. To achieve this, an extra rule is used when signed integers are shifted to the right:
|
||||||
|
|
||||||
|
第二,由于使用二进制补码表示,我们可以和正数一样对负数进行按位左移右移的,同样也是左移1位时乘于`2`,右移1位时除于`2`。要达到此目的,对有符整型的右移有一个特别的要求:
|
||||||
|
|
||||||
When you shift signed integers to the right, apply the same rules as for unsigned integers, but fill any empty bits on the left with the sign bit, rather than with a zero.
|
When you shift signed integers to the right, apply the same rules as for unsigned integers, but fill any empty bits on the left with the sign bit, rather than with a zero.
|
||||||
|
|
||||||
|
对有符整型按位右移时,使用符号位(正数为`0`,负数为`1`)填充空白位。
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
|
|
||||||
This action ensures that signed integers have the same sign after they are shifted to the right, and is known as an arithmetic shift.
|
This action ensures that signed integers have the same sign after they are shifted to the right, and is known as an arithmetic shift.
|
||||||
|
|
||||||
|
这就确保了在右移的过程中,有符整型的符号不会发生变化。这称为算术移位。
|
||||||
|
|
||||||
Because of the special way that positive and negative numbers are stored, shifting either of them to the right moves them closer to zero. Keeping the sign bit the same during this shift means that negative integers remain negative as their value moves closer to zero.
|
Because of the special way that positive and negative numbers are stored, shifting either of them to the right moves them closer to zero. Keeping the sign bit the same during this shift means that negative integers remain negative as their value moves closer to zero.
|
||||||
|
|
||||||
# Overflow Operators
|
正因为正数和负数特殊的存储方式,向右移位使它接近于`0`。移位过程中保持符号会不变,负数在接近`0`的过程中一直是负数。
|
||||||
|
|
||||||
|
## Overflow Operators
|
||||||
|
|
||||||
|
<a name="overflow_operators"></a>
|
||||||
|
## 溢出运算符
|
||||||
|
|
||||||
If you try to insert a number into an integer constant or variable that cannot hold that value, by default Swift reports an error rather than allowing an invalid value to be created. This behavior gives extra safety when you work with numbers that are too large or too small.
|
If you try to insert a number into an integer constant or variable that cannot hold that value, by default Swift reports an error rather than allowing an invalid value to be created. This behavior gives extra safety when you work with numbers that are too large or too small.
|
||||||
|
|
||||||
|
默认情况下,当你往一个整型常量或变量赋于一个它不能承载的大数时,Swift不会让你这么干的,它会报错。这样,在操作过大或过小的数的时候就很安全了。
|
||||||
|
|
||||||
For example, the Int16 integer type can hold any signed integer number between -32768 and 32767. Trying to set a UInt16 constant or variable to a number outside of this range causes an error:
|
For example, the Int16 integer type can hold any signed integer number between -32768 and 32767. Trying to set a UInt16 constant or variable to a number outside of this range causes an error:
|
||||||
|
|
||||||
|
例如,`Int16`整型能承载的整数范围是`-32768`到`32767`,如果给它赋上超过这个范围的数,就会报错:
|
||||||
|
|
||||||
```
|
```
|
||||||
var potentialOverflow = Int16.max
|
var potentialOverflow = Int16.max
|
||||||
// potentialOverflow equals 32767, which is the largest value an Int16 can hold
|
// potentialOverflow 等于 32767, 这是 Int16 能承载的最大整数
|
||||||
potentialOverflow += 1
|
potentialOverflow += 1
|
||||||
// this causes an error
|
// 噢, 出错了
|
||||||
```
|
```
|
||||||
|
|
||||||
Providing error handling when values get too large or too small gives you much more flexibility when coding for boundary value conditions.
|
Providing error handling when values get too large or too small gives you much more flexibility when coding for boundary value conditions.
|
||||||
|
|
||||||
|
对过大或过小的数值进行错误处理让你的数值边界条件更灵活。
|
||||||
|
|
||||||
However, when you specifically want an overflow condition to truncate the number of available bits, you can opt in to this behavior rather than triggering an error. Swift provides five arithmetic overflow operators that opt in to the overflow behavior for integer calculations. These operators all begin with an ampersand (&):
|
However, when you specifically want an overflow condition to truncate the number of available bits, you can opt in to this behavior rather than triggering an error. Swift provides five arithmetic overflow operators that opt in to the overflow behavior for integer calculations. These operators all begin with an ampersand (&):
|
||||||
|
|
||||||
- Overflow addition (&+)
|
当然,你有意在溢出时对有效位进行截断,你可采用溢出运算,而非错误处理。Swfit为整型计算提供了5个`&`符号开头的溢出运算符。
|
||||||
- Overflow subtraction (&-)
|
|
||||||
- Overflow multiplication (&*)
|
|
||||||
- Overflow division (&/)
|
|
||||||
- Overflow remainder (&%)
|
|
||||||
|
|
||||||
## Value Overflow
|
- 溢出加法 `&+`
|
||||||
|
- 溢出减法 `&-`
|
||||||
|
- 溢出乘法 `&*`
|
||||||
|
- 溢出除法 `&/`
|
||||||
|
- 溢出求余 `&%`
|
||||||
|
|
||||||
|
### Value Overflow
|
||||||
|
### 值的上溢出
|
||||||
|
|
||||||
Here’s an example of what happens when an unsigned value is allowed to overflow, using the overflow addition operator (&+):
|
Here’s an example of what happens when an unsigned value is allowed to overflow, using the overflow addition operator (&+):
|
||||||
|
|
||||||
|
下面例子使用了溢出加法`&+`来解剖的无符整数的上溢出
|
||||||
|
|
||||||
```
|
```
|
||||||
var willOverflow = UInt8.max
|
var willOverflow = UInt8.max
|
||||||
// willOverflow equals 255, which is the largest value a UInt8 can hold
|
// willOverflow 等于UInt8的最大整数 255
|
||||||
willOverflow = willOverflow &+ 1
|
willOverflow = willOverflow &+ 1
|
||||||
// willOverflow is now equal to 0
|
// 这时候 willOverflow 等于 0
|
||||||
```
|
```
|
||||||
|
|
||||||
The variable willOverflow is initialized with the largest value a UInt8 can hold (255, or 11111111 in binary). It is then incremented by 1 using the overflow addition operator (&+). This pushes its binary representation just over the size that a UInt8 can hold, causing it to overflow beyond its bounds, as shown in the diagram below. The value that remains within the bounds of the UInt8 after the overflow addition is 00000000, or zero:
|
The variable willOverflow is initialized with the largest value a UInt8 can hold (255, or 11111111 in binary). It is then incremented by 1 using the overflow addition operator (&+). This pushes its binary representation just over the size that a UInt8 can hold, causing it to overflow beyond its bounds, as shown in the diagram below. The value that remains within the bounds of the UInt8 after the overflow addition is 00000000, or zero:
|
||||||
|
|
||||||
|
`willOverflow`用`Int8`所能承载的最大值`255`(二进制`11111111`),然后用`&+`加1。然后`UInt8`就无法表达这个新值的二进制了,也就导致了这个新值上溢出了,大家可以看下图。溢出后,新值在`UInt8`的承载范围内的那部分是`00000000`,也就是`0`。
|
||||||
|
|
||||||

|

|
||||||
Value Underflow
|
|
||||||
|
### Value Underflow
|
||||||
|
### 值的下溢出
|
||||||
|
|
||||||
Numbers can also become too small to fit in their type’s maximum bounds. Here’s an example.
|
Numbers can also become too small to fit in their type’s maximum bounds. Here’s an example.
|
||||||
|
数值也有可能因为太小而越界。举个例子:
|
||||||
|
|
||||||
The smallest value that a UInt8 can hold is 0 (which is 00000000 in eight-bit binary form). If you subtract 1 from 00000000 using the overflow subtraction operator, the number will overflow back round to 11111111, or 255 in decimal:
|
The smallest value that a UInt8 can hold is 0 (which is 00000000 in eight-bit binary form). If you subtract 1 from 00000000 using the overflow subtraction operator, the number will overflow back round to 11111111, or 255 in decimal:
|
||||||
|
|
||||||
|
`UInt8`的最小值是`0`(二进制为`00000000`)。使用`&-`进行溢出减1,就会得到二进制的`11111111`即十进制的`255`。
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
|
|
||||||
Here’s how that looks in Swift code:
|
Here’s how that looks in Swift code:
|
||||||
|
Swift代码是这样的:
|
||||||
|
|
||||||
```
|
```
|
||||||
var willUnderflow = UInt8.min
|
var willUnderflow = UInt8.min
|
||||||
// willUnderflow equals 0, which is the smallest value a UInt8 can hold
|
// willUnderflow 等于UInt8的最小值0
|
||||||
willUnderflow = willUnderflow &- 1
|
willUnderflow = willUnderflow &- 1
|
||||||
// willUnderflow is now equal to 255
|
// 此时 willUnderflow 等于 255
|
||||||
```
|
```
|
||||||
|
|
||||||
A similar underflow occurs for signed integers. All subtraction for signed integers is performed as straight binary subtraction, with the sign bit included as part of the numbers being subtracted, as described in Bitwise Left and Right Shift Operators. The smallest number that an Int8 can hold is -128, which is 10000000 in binary. Subtracting 1 from this binary number with the overflow operator gives a binary value of 01111111, which toggles the sign bit and gives positive 127, the largest positive value that an Int8 can hold:
|
A similar underflow occurs for signed integers. All subtraction for signed integers is performed as straight binary subtraction, with the sign bit included as part of the numbers being subtracted, as described in Bitwise Left and Right Shift Operators. The smallest number that an Int8 can hold is -128, which is 10000000 in binary. Subtracting 1 from this binary number with the overflow operator gives a binary value of 01111111, which toggles the sign bit and gives positive 127, the largest positive value that an Int8 can hold:
|
||||||
|
|
||||||
|
有符整型也有类似的下溢出,有符整型所有的减法也都是对包括在符号位在内的二进制数进行二进制减法的,这在 "按位左移/右移运算符" 一节提到过。最小的有符整数是`-128`,即二进制的`10000000`。用溢出减法减去去1后,变成了`01111111`,即UInt8所能承载的最大整数`127`。
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
Here’s the same thing in Swift code:
|
Here’s the same thing in Swift code:
|
||||||
|
|
||||||
|
来看看Swift代码:
|
||||||
|
|
||||||
```
|
```
|
||||||
var signedUnderflow = Int8.min
|
var signedUnderflow = Int8.min
|
||||||
// signedUnderflow equals -128, which is the smallest value an Int8 can hold
|
// signedUnderflow 等于最小的有符整数 -128
|
||||||
signedUnderflow = signedUnderflow &- 1
|
signedUnderflow = signedUnderflow &- 1
|
||||||
// signedUnderflow is now equal to 127
|
// 如今 signedUnderflow 等于 127
|
||||||
```
|
```
|
||||||
|
|
||||||
The end result of the overflow and underflow behavior described above is that for both signed and unsigned integers, overflow always wraps around from the largest valid integer value back to the smallest, and underflow always wraps around from the smallest value to the largest.
|
The end result of the overflow and underflow behavior described above is that for both signed and unsigned integers, overflow always wraps around from the largest valid integer value back to the smallest, and underflow always wraps around from the smallest value to the largest.
|
||||||
|
|
||||||
## Division by Zero
|
### Division by Zero
|
||||||
|
### 除零溢出
|
||||||
|
|
||||||
Dividing a number by zero (i / 0), or trying to calculate remainder by zero (i % 0), causes an error:
|
Dividing a number by zero(i / 0), or trying to calculate remainder by zero(i % 0), causes an error:
|
||||||
|
|
||||||
|
一个数除于0 `i / 0`,或者对0求余数 `i % 0`,就会产生一个错误。
|
||||||
|
|
||||||
```
|
```
|
||||||
let x = 1
|
let x = 1
|
||||||
@ -294,45 +371,69 @@ let y = x / 0
|
|||||||
|
|
||||||
However, the overflow versions of these operators (&/ and &%) return a value of zero if you divide by zero:
|
However, the overflow versions of these operators (&/ and &%) return a value of zero if you divide by zero:
|
||||||
|
|
||||||
|
使用它们对应的可溢出的版本的运算符`&/`和`&%`进行除0操作时就会得到`0`值。
|
||||||
|
|
||||||
```
|
```
|
||||||
let x = 1
|
let x = 1
|
||||||
let y = x &/ 0
|
let y = x &/ 0
|
||||||
// y is equal to 0
|
// y 等于 0
|
||||||
```
|
```
|
||||||
|
|
||||||
# Precedence and Associativity
|
## Precedence and Associativity
|
||||||
|
|
||||||
|
<a name="precedence_and_associativity"></a>
|
||||||
|
## 优先级和结合性
|
||||||
|
|
||||||
Operator precedence gives some operators higher priority than others; these operators are calculated first.
|
Operator precedence gives some operators higher priority than others; these operators are calculated first.
|
||||||
|
|
||||||
|
运算符的优先级使得一些运算符优先于其他运算符,高优先级的运算符会先被计算。
|
||||||
|
|
||||||
Operator associativity defines how operators of the same precedence are grouped together (or associated)—either grouped from the left, or grouped from the right. Think of it as meaning “they associate with the expression to their left,” or “they associate with the expression to their right.”
|
Operator associativity defines how operators of the same precedence are grouped together (or associated)—either grouped from the left, or grouped from the right. Think of it as meaning “they associate with the expression to their left,” or “they associate with the expression to their right.”
|
||||||
|
|
||||||
|
结合性定义相同优先级的运算符在一起时是怎么组合或关联的,是和左边的一组呢,还是和右边的一组。意思就是,到底是和左边的表达式结合呢,还是和右边的表达式结合?
|
||||||
|
|
||||||
It is important to consider each operator’s precedence and associativity when working out the order in which a compound expression will be calculated. Here’s an example. Why does the following expression equal 4?
|
It is important to consider each operator’s precedence and associativity when working out the order in which a compound expression will be calculated. Here’s an example. Why does the following expression equal 4?
|
||||||
|
|
||||||
|
在混合表达式中,运算符的优先级和结合性是非常重要的。举个例子,为什么下列表达式的结果为`4`?
|
||||||
|
|
||||||
```
|
```
|
||||||
2 + 3 * 4 % 5
|
2 + 3 * 4 % 5
|
||||||
// this equals 4
|
// 结果是 4
|
||||||
```
|
```
|
||||||
|
|
||||||
Taken strictly from left to right, you might expect this to read as follows:
|
Taken strictly from left to right, you might expect this to read as follows:
|
||||||
|
|
||||||
2 plus 3 equals 5;
|
如果严格地从左计算到右,计算过程会是这样:
|
||||||
5 times 4 equals 20;
|
|
||||||
20 remainder 5 equals 0
|
- 2 plus 3 equals 5;
|
||||||
|
- 2 + 3 = 5
|
||||||
|
- 5 times 4 equals 20;
|
||||||
|
- 5 * 4 = 20
|
||||||
|
- 20 remainder 5 equals 0
|
||||||
|
- 20 / 5 = 4 余 0
|
||||||
|
|
||||||
However, the actual answer is 4, not 0. Higher-precedence operators are evaluated before lower-precedence ones. In Swift, as in C, the multiplication operator (*) and the remainder operator (%) have a higher precedence than the addition operator (+). As a result, they are both evaluated before the addition is considered.
|
However, the actual answer is 4, not 0. Higher-precedence operators are evaluated before lower-precedence ones. In Swift, as in C, the multiplication operator (*) and the remainder operator (%) have a higher precedence than the addition operator (+). As a result, they are both evaluated before the addition is considered.
|
||||||
|
|
||||||
|
但是正确答案是`4`而不是`0`。优先级高的运算符要先计算,在Swift和C语言中,都是先乘除后加减的。所以,执行完乘法和求余运算才能执行加减运算。
|
||||||
|
|
||||||
However, multiplication and remainder have the same precedence as each other. To work out the exact evaluation order to use, you also need to consider their associativity. Multiplication and remainder both associate with the expression to their left. Think of this as adding implicit parentheses around these parts of the expression, starting from their left:
|
However, multiplication and remainder have the same precedence as each other. To work out the exact evaluation order to use, you also need to consider their associativity. Multiplication and remainder both associate with the expression to their left. Think of this as adding implicit parentheses around these parts of the expression, starting from their left:
|
||||||
|
|
||||||
|
乘法和求余拥有相同的优先级,在运算过程中,我们还需要结合性,乘法和求余运算都是左结合的。这相当于在表达式中有隐藏的括号让运算从左开始。
|
||||||
|
|
||||||
```
|
```
|
||||||
2 + ((3 * 4) % 5)
|
2 + ((3 * 4) % 5)
|
||||||
```
|
```
|
||||||
|
|
||||||
(3 * 4) is 12, so this is equivalent to:
|
(3 * 4) is 12, so this is equivalent to:
|
||||||
|
3 * 4 = 12,所以这相当于:
|
||||||
|
|
||||||
|
|
||||||
```
|
```
|
||||||
2 + (12 % 5)
|
2 + (12 % 5)
|
||||||
```
|
```
|
||||||
|
|
||||||
(12 % 5) is 2, so this is equivalent to:
|
(12 % 5) is 2, so this is equivalent to:
|
||||||
|
12 % 5 = 2,所这又相当于
|
||||||
|
|
||||||
```
|
```
|
||||||
2 + 2
|
2 + 2
|
||||||
@ -340,139 +441,253 @@ However, multiplication and remainder have the same precedence as each other. To
|
|||||||
|
|
||||||
This calculation yields the final answer of 4.
|
This calculation yields the final answer of 4.
|
||||||
|
|
||||||
For a complete list of Swift operator precedences and associativity rules, see Expressions.
|
计算结果为 4。
|
||||||
|
|
||||||
|
For a complete list of Swift operator precedences and associativity rules, see [Expressions](Expressions).
|
||||||
|
|
||||||
|
查阅Swift运算符的优先级和结合性的完整列表,请看[表达式](../chapter3/04_Expressions.html)。
|
||||||
|
|
||||||
> NOTE
|
> NOTE
|
||||||
|
|
||||||
> Swift’s operator precedences and associativity rules are simpler and more predictable than those found in C and Objective-C. However, this means that they are not the same as in C-based languages. Be careful to ensure that operator interactions still behave in the way you intend when porting existing code to Swift.
|
> Swift’s operator precedences and associativity rules are simpler and more predictable than those found in C and Objective-C. However, this means that they are not the same as in C-based languages. Be careful to ensure that operator interactions still behave in the way you intend when porting existing code to Swift.
|
||||||
|
|
||||||
Operator Functions
|
> 注意:
|
||||||
|
Swift的运算符较C语言和Objective-C来得更简单和保守,这意味着跟基于C的语言可能不一样。所以,在移植已有代码到Swift时,注意去确保代码按你想的那样去执行。
|
||||||
|
|
||||||
|
## Operator Functions
|
||||||
|
|
||||||
|
<a name="operator_functions"></a>
|
||||||
|
## 运算符函数
|
||||||
|
|
||||||
Classes and structures can provide their own implementations of existing operators. This is known as overloading the existing operators.
|
Classes and structures can provide their own implementations of existing operators. This is known as overloading the existing operators.
|
||||||
|
|
||||||
|
让已有的运算符也可以对自定义的类和结构进行运算,这称为运算符重载。
|
||||||
|
|
||||||
The example below shows how to implement the arithmetic addition operator (+) for a custom structure. The arithmetic addition operator is a binary operator because it operates on two targets and is said to be infix because it appears in between those two targets.
|
The example below shows how to implement the arithmetic addition operator (+) for a custom structure. The arithmetic addition operator is a binary operator because it operates on two targets and is said to be infix because it appears in between those two targets.
|
||||||
|
|
||||||
The example defines a Vector2D structure for a two-dimensional position vector (x, y), followed by a definition of an operator function to add together instances of the Vector2D structure:
|
The example defines a Vector2D structure for a two-dimensional position vector (x, y), followed by a definition of an operator function to add together instances of the Vector2D structure:
|
||||||
|
|
||||||
|
这个例子展示了如何用`+`让一个自定义的结构做加法。算术运算符`+`是一个两目运算符,因为它有两个操作数,而且它必须出现在两个操作数之间。
|
||||||
|
|
||||||
|
例子中定义了一个名为`Vector2D`的二维坐标向量 `(x,y)` 的结构,然后定义了让两个`Vector2D`的对象相加的运算符函数。
|
||||||
|
|
||||||
|
```
|
||||||
struct Vector2D {
|
struct Vector2D {
|
||||||
var x = 0.0, y = 0.0
|
var x = 0.0, y = 0.0
|
||||||
}
|
}
|
||||||
@infix func + (left: Vector2D, right: Vector2D) -> Vector2D {
|
@infix func + (left: Vector2D, right: Vector2D) -> Vector2D {
|
||||||
return Vector2D(x: left.x + right.x, y: left.y + right.y)
|
return Vector2D(x: left.x + right.x, y: left.y + right.y)
|
||||||
}
|
}
|
||||||
|
```
|
||||||
|
|
||||||
The operator function is defined as a global function called +, which takes two input parameters of type Vector2D and returns a single output value, also of type Vector2D. You implement an infix operator by writing the @infix attribute before the func keyword when declaring the operator function.
|
The operator function is defined as a global function called +, which takes two input parameters of type Vector2D and returns a single output value, also of type Vector2D. You implement an infix operator by writing the @infix attribute before the func keyword when declaring the operator function.
|
||||||
|
|
||||||
|
该运算符函数定义了一个全局的`+`函数,这个函数需要两个`Vector2D`类型的参数,返回值也是`Vector2D`类型。需要定义和实现一个中置运算的时候,在关键字`func`之前写上属性 `@infix` 就可以了。
|
||||||
|
|
||||||
In this implementation, the input parameters are named left and right to represent the Vector2D instances that will be on the left side and right side of the + operator. The function returns a new Vector2D instance, whose x and y properties are initialized with the sum of the x and y properties from the two Vector2D instances that are added together.
|
In this implementation, the input parameters are named left and right to represent the Vector2D instances that will be on the left side and right side of the + operator. The function returns a new Vector2D instance, whose x and y properties are initialized with the sum of the x and y properties from the two Vector2D instances that are added together.
|
||||||
|
|
||||||
|
在这个代码实现中,参数被命名为了`left`和`right`,代表`+`左边和右边的两个`Vector2D`对象。函数返回了一个新的`Vector2D`的对象,这个对象的`x`和`y`分别等于两个参数对象的`x`和`y`的和。
|
||||||
|
|
||||||
The function is defined globally, rather than as a method on the Vector2D structure, so that it can be used as an infix operator between existing Vector2D instances:
|
The function is defined globally, rather than as a method on the Vector2D structure, so that it can be used as an infix operator between existing Vector2D instances:
|
||||||
|
|
||||||
|
这个函数是全局的,而不是`Vector2D`结构的成员方法,所以任意两个`Vector2D`对象都可以使用这个中置运算符。
|
||||||
|
|
||||||
|
```
|
||||||
let vector = Vector2D(x: 3.0, y: 1.0)
|
let vector = Vector2D(x: 3.0, y: 1.0)
|
||||||
let anotherVector = Vector2D(x: 2.0, y: 4.0)
|
let anotherVector = Vector2D(x: 2.0, y: 4.0)
|
||||||
let combinedVector = vector + anotherVector
|
let combinedVector = vector + anotherVector
|
||||||
// combinedVector is a Vector2D instance with values of (5.0, 5.0)
|
// combinedVector 是一个新的Vector2D, 值为 (5.0, 5.0)
|
||||||
|
```
|
||||||
|
|
||||||
This example adds together the vectors (3.0, 1.0) and (2.0, 4.0) to make the vector (5.0, 5.0), as illustrated below.
|
This example adds together the vectors (3.0, 1.0) and (2.0, 4.0) to make the vector (5.0, 5.0), as illustrated below.
|
||||||
|
|
||||||
|
这个例子实现两个向量 `(3.0,1.0)` 和 `(2.0,4.0)` 相加,得到向量 `(5.0,5.0)` 的过程。如下图示:
|
||||||
|
|
||||||

|

|
||||||
Prefix and Postfix Operators
|
|
||||||
|
### Prefix and Postfix Operators
|
||||||
|
### 前置和后置运算符
|
||||||
|
|
||||||
The example shown above demonstrates a custom implementation of a binary infix operator. Classes and structures can also provide implementations of the standard unary operators. Unary operators operate on a single target. They are prefix if they precede their target (such as -a) and postfix operators if they follow their target (such as i++).
|
The example shown above demonstrates a custom implementation of a binary infix operator. Classes and structures can also provide implementations of the standard unary operators. Unary operators operate on a single target. They are prefix if they precede their target (such as -a) and postfix operators if they follow their target (such as i++).
|
||||||
|
|
||||||
You implement a prefix or postfix unary operator by writing the @prefix or @postfix attribute before the func keyword when declaring the operator function:
|
You implement a prefix or postfix unary operator by writing the @prefix or @postfix attribute before the func keyword when declaring the operator function:
|
||||||
|
|
||||||
|
上个例子演示了一个双目中置运算符的自定义实现,同样我们也可以玩标准单目运算符的实现。单目运算符只有一个操作数,在操作数之前就是前置的,如`-a`; 在操作数之后就是后置的,如`i++`。
|
||||||
|
|
||||||
|
实现一个前置或后置运算符时,在定义该运算符的时候于关键字`func`之前标注 `@prefix` 或 `@postfix` 属性。
|
||||||
|
|
||||||
|
```
|
||||||
@prefix func - (vector: Vector2D) -> Vector2D {
|
@prefix func - (vector: Vector2D) -> Vector2D {
|
||||||
return Vector2D(x: -vector.x, y: -vector.y)
|
return Vector2D(x: -vector.x, y: -vector.y)
|
||||||
}
|
}
|
||||||
|
```
|
||||||
|
|
||||||
The example above implements the unary minus operator (-a) for Vector2D instances. The unary minus operator is a prefix operator, and so this function has to be qualified with the @prefix attribute.
|
The example above implements the unary minus operator (-a) for Vector2D instances. The unary minus operator is a prefix operator, and so this function has to be qualified with the @prefix attribute.
|
||||||
|
|
||||||
|
这段代码为`Vector2D`类型提供了单目减运算`-a`,`@prefix`属性表明这是个前置运算符。
|
||||||
|
|
||||||
For simple numeric values, the unary minus operator converts positive numbers into their negative equivalent and vice versa. The corresponding implementation for Vector2D instances performs this operation on both the x and y properties:
|
For simple numeric values, the unary minus operator converts positive numbers into their negative equivalent and vice versa. The corresponding implementation for Vector2D instances performs this operation on both the x and y properties:
|
||||||
|
|
||||||
|
对于数值,单目减运算符可以把正数变负数,把负数变正数。对于`Vector2D`,单目减运算将其`x`和`y`都进进行单目减运算。
|
||||||
|
|
||||||
|
```
|
||||||
let positive = Vector2D(x: 3.0, y: 4.0)
|
let positive = Vector2D(x: 3.0, y: 4.0)
|
||||||
let negative = -positive
|
let negative = -positive
|
||||||
// negative is a Vector2D instance with values of (-3.0, -4.0)
|
// negative 为 (-3.0, -4.0)
|
||||||
let alsoPositive = -negative
|
let alsoPositive = -negative
|
||||||
// alsoPositive is a Vector2D instance with values of (3.0, 4.0)
|
// alsoPositive 为 (3.0, 4.0)
|
||||||
Compound Assignment Operators
|
```
|
||||||
|
|
||||||
|
### Compound Assignment Operators
|
||||||
|
### 组合赋值运算符
|
||||||
|
|
||||||
Compound assignment operators combine assignment (=) with another operation. For example, the addition assignment operator (+=) combines addition and assignment into a single operation. Operator functions that implement compound assignment must be qualified with the @assignment attribute. You must also mark a compound assignment operator’s left input parameter as inout, because the parameter’s value will be modified directly from within the operator function.
|
Compound assignment operators combine assignment (=) with another operation. For example, the addition assignment operator (+=) combines addition and assignment into a single operation. Operator functions that implement compound assignment must be qualified with the @assignment attribute. You must also mark a compound assignment operator’s left input parameter as inout, because the parameter’s value will be modified directly from within the operator function.
|
||||||
|
|
||||||
The example below implements an addition assignment operator function for Vector2D instances:
|
The example below implements an addition assignment operator function for Vector2D instances:
|
||||||
|
|
||||||
|
组合赋值是其他运算符和赋值运算符一起执行的运算。如`+=`把加运算和赋值运算组合成一个操作。实现一个组合赋值符号需要使用`@assignment`属性,还需要把运算符的左参数设置成`inout`,因为这个参数会在运算符函数内直接修改它的值。
|
||||||
|
|
||||||
|
```
|
||||||
@assignment func += (inout left: Vector2D, right: Vector2D) {
|
@assignment func += (inout left: Vector2D, right: Vector2D) {
|
||||||
left = left + right
|
left = left + right
|
||||||
}
|
}
|
||||||
|
```
|
||||||
|
|
||||||
Because an addition operator was defined earlier, you don’t need to reimplement the addition process here. Instead, the addition assignment operator function takes advantage of the existing addition operator function, and uses it to set the left value to be the left value plus the right value:
|
Because an addition operator was defined earlier, you don’t need to reimplement the addition process here. Instead, the addition assignment operator function takes advantage of the existing addition operator function, and uses it to set the left value to be the left value plus the right value:
|
||||||
|
|
||||||
|
因为加法运算在之前定义过了,这里无需重新定义。所以,加赋运算符函数使用已经存在的高级加法运算符函数来执行左值加右值的运算。
|
||||||
|
|
||||||
|
```
|
||||||
var original = Vector2D(x: 1.0, y: 2.0)
|
var original = Vector2D(x: 1.0, y: 2.0)
|
||||||
let vectorToAdd = Vector2D(x: 3.0, y: 4.0)
|
let vectorToAdd = Vector2D(x: 3.0, y: 4.0)
|
||||||
original += vectorToAdd
|
original += vectorToAdd
|
||||||
// original now has values of (4.0, 6.0)
|
// original 现在为 (4.0, 6.0)
|
||||||
|
```
|
||||||
|
|
||||||
You can combine the @assignment attribute with either the @prefix or @postfix attribute, as in this implementation of the prefix increment operator (++a) for Vector2D instances:
|
You can combine the @assignment attribute with either the @prefix or @postfix attribute, as in this implementation of the prefix increment operator (++a) for Vector2D instances:
|
||||||
|
|
||||||
|
你可以将 `@assignment` 属性和 `@prefix` 或 `@postfix` 属性起来组合,实现一个`Vector2D`的前置运算符。
|
||||||
|
|
||||||
|
```
|
||||||
@prefix @assignment func ++ (inout vector: Vector2D) -> Vector2D {
|
@prefix @assignment func ++ (inout vector: Vector2D) -> Vector2D {
|
||||||
vector += Vector2D(x: 1.0, y: 1.0)
|
vector += Vector2D(x: 1.0, y: 1.0)
|
||||||
return vector
|
return vector
|
||||||
}
|
}
|
||||||
|
```
|
||||||
|
|
||||||
The prefix increment operator function above takes advantage of the addition assignment operator defined earlier. It adds a Vector2D with x and y values of 1.0 to the Vector2D on which it is called, and returns the result:
|
The prefix increment operator function above takes advantage of the addition assignment operator defined earlier. It adds a Vector2D with x and y values of 1.0 to the Vector2D on which it is called, and returns the result:
|
||||||
|
|
||||||
|
这个前置使用了已经定义好的高级加赋运算,将自己加上一个值为 `(1.0,1.0)` 的对象然后赋给自己,然后再将自己返回。
|
||||||
|
|
||||||
|
```
|
||||||
var toIncrement = Vector2D(x: 3.0, y: 4.0)
|
var toIncrement = Vector2D(x: 3.0, y: 4.0)
|
||||||
let afterIncrement = ++toIncrement
|
let afterIncrement = ++toIncrement
|
||||||
// toIncrement now has values of (4.0, 5.0)
|
// toIncrement 现在是 (4.0, 5.0)
|
||||||
// afterIncrement also has values of (4.0, 5.0)
|
// afterIncrement 现在也是 (4.0, 5.0)
|
||||||
NOTE
|
```
|
||||||
|
|
||||||
It is not possible to overload the default assignment operator (=). Only the compound assignment operators can be overloaded. Similarly, the ternary conditional operator (a ? b : c) cannot be overloaded.
|
> NOTE
|
||||||
|
|
||||||
Equivalence Operators
|
> It is not possible to overload the default assignment operator (=). Only the compound assignment operators can be overloaded. Similarly, the ternary conditional operator (a ? b : c) cannot be overloaded.
|
||||||
|
|
||||||
|
>注意:
|
||||||
|
默认的赋值符是不可重载的。只有组合赋值符可以重载。三目条件运算符 `a?b:c` 也是不可重载。
|
||||||
|
|
||||||
|
### Equivalence Operators
|
||||||
|
### 比较运算符
|
||||||
|
|
||||||
Custom classes and structures do not receive a default implementation of the equivalence operators, known as the “equal to” operator (==) and “not equal to” operator (!=). It is not possible for Swift to guess what would qualify as “equal” for your own custom types, because the meaning of “equal” depends on the roles that those types play in your code.
|
Custom classes and structures do not receive a default implementation of the equivalence operators, known as the “equal to” operator (==) and “not equal to” operator (!=). It is not possible for Swift to guess what would qualify as “equal” for your own custom types, because the meaning of “equal” depends on the roles that those types play in your code.
|
||||||
|
|
||||||
|
Swift无所知道自定义类型是否相等或不等,因为等于或者不等于由你的代码说了算了。所以自定义的类和结构要使用比较符`==`或`!=`就需要重载。
|
||||||
|
|
||||||
To use the equivalence operators to check for equivalence of your own custom type, provide an implementation of the operators in the same way as for other infix operators:
|
To use the equivalence operators to check for equivalence of your own custom type, provide an implementation of the operators in the same way as for other infix operators:
|
||||||
|
|
||||||
|
定义相等运算符函数跟定义其他中置运算符雷同:
|
||||||
|
|
||||||
|
```
|
||||||
@infix func == (left: Vector2D, right: Vector2D) -> Bool {
|
@infix func == (left: Vector2D, right: Vector2D) -> Bool {
|
||||||
return (left.x == right.x) && (left.y == right.y)
|
return (left.x == right.x) && (left.y == right.y)
|
||||||
}
|
}
|
||||||
|
|
||||||
@infix func != (left: Vector2D, right: Vector2D) -> Bool {
|
@infix func != (left: Vector2D, right: Vector2D) -> Bool {
|
||||||
return !(left == right)
|
return !(left == right)
|
||||||
}
|
}
|
||||||
|
```
|
||||||
|
|
||||||
The above example implements an “equal to” operator (==) to check if two Vector2D instances have equivalent values. In the context of Vector2D, it makes sense to consider “equal” as meaning “both instances have the same x values and y values”, and so this is the logic used by the operator implementation. The example also implements the “not equal to” operator (!=), which simply returns the inverse of the result of the “equal to” operator.
|
The above example implements an “equal to” operator (==) to check if two Vector2D instances have equivalent values. In the context of Vector2D, it makes sense to consider “equal” as meaning “both instances have the same x values and y values”, and so this is the logic used by the operator implementation. The example also implements the “not equal to” operator (!=), which simply returns the inverse of the result of the “equal to” operator.
|
||||||
|
|
||||||
|
上述代码实现了相等运算符`==`来判断两个`Vector2D`对象是否有相等的值,相等的概念就是他们有相同的`x`值和相同的`y`值,我们就用这个逻辑来实现。接着使用`==`的结果实现了不相等运算符`!=`。
|
||||||
|
|
||||||
You can now use these operators to check whether two Vector2D instances are equivalent:
|
You can now use these operators to check whether two Vector2D instances are equivalent:
|
||||||
|
|
||||||
|
现在我们可以使用这两个运算符来判断两个`Vector2D`对象是否相等。
|
||||||
|
|
||||||
|
```
|
||||||
let twoThree = Vector2D(x: 2.0, y: 3.0)
|
let twoThree = Vector2D(x: 2.0, y: 3.0)
|
||||||
let anotherTwoThree = Vector2D(x: 2.0, y: 3.0)
|
let anotherTwoThree = Vector2D(x: 2.0, y: 3.0)
|
||||||
if twoThree == anotherTwoThree {
|
if twoThree == anotherTwoThree {
|
||||||
println("These two vectors are equivalent.")
|
println("这两个向量是相等的.")
|
||||||
}
|
}
|
||||||
// prints "These two vectors are equivalent."
|
// prints "这两个向量是相等的."
|
||||||
Custom Operators
|
```
|
||||||
|
|
||||||
|
### Custom Operators
|
||||||
|
### 自定义运算符
|
||||||
|
|
||||||
You can declare and implement your own custom operators in addition to the standard operators provided by Swift. Custom operators can be defined only with the characters / = - + * % < > ! & | ^ . ~.
|
You can declare and implement your own custom operators in addition to the standard operators provided by Swift. Custom operators can be defined only with the characters / = - + * % < > ! & | ^ . ~.
|
||||||
|
|
||||||
|
标准的运算符不够玩,那你可以声明一些个性的运算符,但个性的运算符只能使用这些字符 `/ = - + * % < >!& | ^。~`。
|
||||||
|
|
||||||
New operators are declared at a global level using the operator keyword, and can be declared as prefix, infix or postfix:
|
New operators are declared at a global level using the operator keyword, and can be declared as prefix, infix or postfix:
|
||||||
|
|
||||||
|
新的运算符声明需在全局域使用`operator`关键字声明,可以声明为前置,中置或后置的。
|
||||||
|
|
||||||
|
```
|
||||||
operator prefix +++ {}
|
operator prefix +++ {}
|
||||||
|
```
|
||||||
|
|
||||||
The example above defines a new prefix operator called +++. This operator does not have an existing meaning in Swift, and so it is given its own custom meaning below in the specific context of working with Vector2D instances. For the purposes of this example, +++ is treated as a new “prefix doubling incrementer” operator. It doubles the x and y values of a Vector2D instance, by adding the vector to itself with the addition assignment operator defined earlier:
|
The example above defines a new prefix operator called +++. This operator does not have an existing meaning in Swift, and so it is given its own custom meaning below in the specific context of working with Vector2D instances. For the purposes of this example, +++ is treated as a new “prefix doubling incrementer” operator. It doubles the x and y values of a Vector2D instance, by adding the vector to itself with the addition assignment operator defined earlier:
|
||||||
|
|
||||||
|
这段代码定义了一个新的前置运算符叫`+++`,此前Swift并不存在这个运算符。此处为了演示,我们让`+++`对`Vector2D`对象的操作定义为 `双自增` 这样一个独有的操作,这个操作使用了之前定义的加赋运算实现了自已加上自己然后返回的运算。
|
||||||
|
|
||||||
|
```
|
||||||
@prefix @assignment func +++ (inout vector: Vector2D) -> Vector2D {
|
@prefix @assignment func +++ (inout vector: Vector2D) -> Vector2D {
|
||||||
vector += vector
|
vector += vector
|
||||||
return vector
|
return vector
|
||||||
}
|
}
|
||||||
|
```
|
||||||
|
|
||||||
This implementation of +++ is very similar to the implementation of ++ for Vector2D, except that this operator function adds the vector to itself, rather than adding Vector2D(1.0, 1.0):
|
This implementation of +++ is very similar to the implementation of ++ for Vector2D, except that this operator function adds the vector to itself, rather than adding Vector2D(1.0, 1.0):
|
||||||
|
|
||||||
|
`Vector2D` 的 `+++` 的实现和 `++` 的实现很接近, 唯一不同的前者是加自己, 后者是加值为 `(1.0, 1.0)` 的向量.
|
||||||
|
|
||||||
|
```
|
||||||
var toBeDoubled = Vector2D(x: 1.0, y: 4.0)
|
var toBeDoubled = Vector2D(x: 1.0, y: 4.0)
|
||||||
let afterDoubling = +++toBeDoubled
|
let afterDoubling = +++toBeDoubled
|
||||||
// toBeDoubled now has values of (2.0, 8.0)
|
// toBeDoubled 现在是 (2.0, 8.0)
|
||||||
// afterDoubling also has values of (2.0, 8.0)
|
// afterDoubling 现在也是 (2.0, 8.0)
|
||||||
Precedence and Associativity for Custom Infix Operators
|
```
|
||||||
|
|
||||||
Custom infix operators can also specify a precedence and an associativity. See Precedence and Associativity for an explanation of how these two characteristics affect an infix operator’s interaction with other infix operators.
|
### Precedence and Associativity for Custom Infix Operators
|
||||||
|
### 自定义中置运算符的优先级和结合性
|
||||||
|
|
||||||
|
Custom infix operators can also specify a precedence and an associativity. See [Precedence and Associativity](#PrecedenceandAssociativity) for an explanation of how these two characteristics affect an infix operator’s interaction with other infix operators.
|
||||||
|
|
||||||
|
可以为自定义的中置运算符指定优先级和结合性。可以回头看看[优先级和结合性](#PrecedenceandAssociativity)解释这两个因素是如何影响多种中置运算符混合的表达式的计算的。
|
||||||
|
|
||||||
The possible values for associativity are left, right, and none. Left-associative operators associate to the left if written next to other left-associative operators of the same precedence. Similarly, right-associative operators associate to the right if written next to other right-associative operators of the same precedence. Non-associative operators cannot be written next to other operators with the same precedence.
|
The possible values for associativity are left, right, and none. Left-associative operators associate to the left if written next to other left-associative operators of the same precedence. Similarly, right-associative operators associate to the right if written next to other right-associative operators of the same precedence. Non-associative operators cannot be written next to other operators with the same precedence.
|
||||||
|
|
||||||
|
结合性(associativity)的值可取的值有`left`,`right`和`none`。左结合运算符跟其他优先级相同的左结合运算符写在一起时,会跟左边的操作数结合。同理,右结合运算符会跟右边的操作数结合。而非结合运算符不能跟其他相同优先级的运算符写在一起。
|
||||||
|
|
||||||
The associativity value defaults to none if it is not specified. The precedence value defaults to 100 if it is not specified.
|
The associativity value defaults to none if it is not specified. The precedence value defaults to 100 if it is not specified.
|
||||||
|
|
||||||
|
结合性(associativity)的值默认为`none`,优先级(precedence)默认为`100`。
|
||||||
|
|
||||||
The following example defines a new custom infix operator called +-, with left associativity and a precedence of 140:
|
The following example defines a new custom infix operator called +-, with left associativity and a precedence of 140:
|
||||||
|
|
||||||
|
以下例子定义了一个新的中置符`+-`,是左结合的`left`,优先级为`140`。
|
||||||
|
|
||||||
|
```
|
||||||
operator infix +- { associativity left precedence 140 }
|
operator infix +- { associativity left precedence 140 }
|
||||||
func +- (left: Vector2D, right: Vector2D) -> Vector2D {
|
func +- (left: Vector2D, right: Vector2D) -> Vector2D {
|
||||||
return Vector2D(x: left.x + right.x, y: left.y - right.y)
|
return Vector2D(x: left.x + right.x, y: left.y - right.y)
|
||||||
@ -480,5 +695,9 @@ func +- (left: Vector2D, right: Vector2D) -> Vector2D {
|
|||||||
let firstVector = Vector2D(x: 1.0, y: 2.0)
|
let firstVector = Vector2D(x: 1.0, y: 2.0)
|
||||||
let secondVector = Vector2D(x: 3.0, y: 4.0)
|
let secondVector = Vector2D(x: 3.0, y: 4.0)
|
||||||
let plusMinusVector = firstVector +- secondVector
|
let plusMinusVector = firstVector +- secondVector
|
||||||
// plusMinusVector is a Vector2D instance with values of (4.0, -2.0)
|
// plusMinusVector 此时的值为 (4.0, -2.0)
|
||||||
This operator adds together the x values of two vectors, and subtracts the y value of the second vector from the first. Because it is in essence an “additive” operator, it has been given the same associativity and precedence values (left and 140) as default additive infix operators such as + and -. For a complete list of the default Swift operator precedence and associativity settings, see Expressions.
|
```
|
||||||
|
|
||||||
|
This operator adds together the x values of two vectors, and subtracts the y value of the second vector from the first. Because it is in essence an “additive” operator, it has been given the same associativity and precedence values (left and 140) as default additive infix operators such as + and -. For a complete list of the default Swift operator precedence and associativity settings, see [Expressions](Expressions).
|
||||||
|
|
||||||
|
这个运算符把两个向量的`x`相加,把向量的`y`相减。因为他实际是属于加减运算,所以让它保持了和加法一样的结合性和优先级(`left`和`140`)。查阅完整的Swift默认结合性和优先级的设置,请移步[表达式](../chapter3/04_Expressions.html);
|
||||||
Reference in New Issue
Block a user