Files
the-swift-programming-langu…/chapter2/23_Advanced_Operators.html
2014-06-11 09:55:12 +08:00

929 lines
60 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!DOCTYPE HTML>
<html lang="en-US" manifest="../manifest.appcache">
<head prefix="og: http://ogp.me/ns# book: http://ogp.me/ns/book#">
<meta charset="UTF-8">
<title>高级操作符 | Swift 编程语言</title>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<meta name="robots" content="index, follow">
<meta name="author" content="">
<meta name="description" content="Swift 是苹果在 WWDC 2014 上发布的一款全新的编程语言,本书译自苹果官方的 Swift 教程《The Swift Programming Language》。">
<meta name="keywords" content="gitbook,github" >
<meta name="generator" content="www.gitbook.io">
<link rel="next" href="../chapter3/chapter3.html" />
<link rel="prev" href="../chapter2/22_Generics.html" />
<meta property="og:title" content="高级操作符 | Swift 编程语言">
<meta property="og:site_name" content="Swift 编程语言">
<meta property="og:type" content="book">
<meta property="og:locale" content="en_US">
<meta property="book:author" content="https://github.com/">
<meta property="book:tag" content="GitBook">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<link rel="shortcut icon" href="../gitbook/images/favicon.ico" type="image/x-icon">
</head>
<body>
<link rel="stylesheet" href="../gitbook/style.css">
<div class="book" data-level="2.23" data-basepath=".." data-revision="1402451678088">
<div class="book-header">
<!-- Actions Left -->
<a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
<a href="https://github.com/null" target="_blank" class="btn pull-left home-bookmark" aria-label="GitHub home"><i class="fa fa-bookmark-o"></i></a>
<a href="#" class="btn pull-left toggle-search" aria-label="Toggle search"><i class="fa fa-search"></i></a>
<span id="font-settings-wrapper">
<a href="#" class="btn pull-left toggle-font-settings" aria-label="Toggle font settings"><i class="fa fa-font"></i>
</a>
<div class="dropdown-menu font-settings">
<div class="dropdown-caret">
<span class="caret-outer"></span>
<span class="caret-inner"></span>
</div>
<div class="btn-group btn-block">
<button id="reduce-font-size" class="btn btn-default">A</button>
<button id="enlarge-font-size" class="btn btn-default">A</button>
</div>
<ul class="list-group font-family-list">
<li class="list-group-item" data-font="0">Serif</li>
<li class="list-group-item" data-font="1">Sans</li>
</ul>
<div class="btn-group btn-group-xs btn-block color-theme-list">
<button type="button" class="btn btn-default" id="color-theme-preview-0" data-theme="0">White</button>
<button type="button" class="btn btn-default" id="color-theme-preview-1" data-theme="1">Sepia</button>
<button type="button" class="btn btn-default" id="color-theme-preview-2" data-theme="2">Night</button>
</div>
</div>
</span>
<!-- Actions Right -->
<a href="#" target="_blank" class="btn pull-right google-plus-sharing-link sharing-link" data-sharing="google-plus" aria-label="Share on Google Plus"><i class="fa fa-google-plus"></i></a>
<a href="#" target="_blank" class="btn pull-right facebook-sharing-link sharing-link" data-sharing="facebook" aria-label="Share on Facebook"><i class="fa fa-facebook"></i></a>
<a href="#" target="_blank" class="btn pull-right twitter-sharing-link sharing-link" data-sharing="twitter" aria-label="Share on Twitter"><i class="fa fa-twitter"></i></a>
<!-- Title -->
<h1>
<i class="fa fa-spinner fa-spin"></i>
<a href="../" >Swift 编程语言</a>
</h1>
</div>
<div class="book-summary">
<div class="book-search">
<input type="text" placeholder="Search" class="form-control" />
</div>
<ul class="summary">
<li data-level="0" data-path="index.html">
<a href="../"><i class="fa fa-check"></i> Introduction</a>
</li>
<li class="chapter " data-level="1" data-path="chapter1/chapter1.html">
<a href="../chapter1/chapter1.html">
<i class="fa fa-check"></i> <b>1.</b> 欢迎使用 Swift
</a>
<ul class="articles">
<li class="chapter " data-level="1.1" data-path="chapter1/01_swift.html">
<a href="../chapter1/01_swift.html">
<i class="fa fa-check"></i> <b>1.1.</b> 关于 Swift
</a>
</li>
<li class="chapter " data-level="1.2" data-path="chapter1/02_a_swift_tour.html">
<a href="../chapter1/02_a_swift_tour.html">
<i class="fa fa-check"></i> <b>1.2.</b> Swift 初见
</a>
</li>
</ul>
</li>
<li class="chapter " data-level="2" data-path="chapter2/chapter2.html">
<a href="../chapter2/chapter2.html">
<i class="fa fa-check"></i> <b>2.</b> Swift 教程
</a>
<ul class="articles">
<li class="chapter " data-level="2.1" data-path="chapter2/01_The_Basics.html">
<a href="../chapter2/01_The_Basics.html">
<i class="fa fa-check"></i> <b>2.1.</b> 基础部分
</a>
</li>
<li class="chapter " data-level="2.2" data-path="chapter2/02_Basic_Operators.html">
<a href="../chapter2/02_Basic_Operators.html">
<i class="fa fa-check"></i> <b>2.2.</b> 基本运算符
</a>
</li>
<li class="chapter " data-level="2.3" data-path="chapter2/03_Strings_and_Characters.html">
<a href="../chapter2/03_Strings_and_Characters.html">
<i class="fa fa-check"></i> <b>2.3.</b> 字符串和字符
</a>
</li>
<li class="chapter " data-level="2.4" data-path="chapter2/04_Collection_Types.html">
<a href="../chapter2/04_Collection_Types.html">
<i class="fa fa-check"></i> <b>2.4.</b> 集合类型
</a>
</li>
<li class="chapter " data-level="2.5" data-path="chapter2/05_Control_Flow.html">
<a href="../chapter2/05_Control_Flow.html">
<i class="fa fa-check"></i> <b>2.5.</b> 控制流
</a>
</li>
<li class="chapter " data-level="2.6" data-path="chapter2/06_Functions.html">
<a href="../chapter2/06_Functions.html">
<i class="fa fa-check"></i> <b>2.6.</b> 函数
</a>
</li>
<li class="chapter " data-level="2.7" data-path="chapter2/07_Closures.html">
<a href="../chapter2/07_Closures.html">
<i class="fa fa-check"></i> <b>2.7.</b> 闭包
</a>
</li>
<li class="chapter " data-level="2.8" data-path="chapter2/08_Enumerations.html">
<a href="../chapter2/08_Enumerations.html">
<i class="fa fa-check"></i> <b>2.8.</b> 枚举
</a>
</li>
<li class="chapter " data-level="2.9" data-path="chapter2/09_Classes_and_Structures.html">
<a href="../chapter2/09_Classes_and_Structures.html">
<i class="fa fa-check"></i> <b>2.9.</b> 类和结构体
</a>
</li>
<li class="chapter " data-level="2.10" data-path="chapter2/10_Properties.html">
<a href="../chapter2/10_Properties.html">
<i class="fa fa-check"></i> <b>2.10.</b> 属性
</a>
</li>
<li class="chapter " data-level="2.11" data-path="chapter2/11_Methods.html">
<a href="../chapter2/11_Methods.html">
<i class="fa fa-check"></i> <b>2.11.</b> 方法
</a>
</li>
<li class="chapter " data-level="2.12" data-path="chapter2/12_Subscripts.html">
<a href="../chapter2/12_Subscripts.html">
<i class="fa fa-check"></i> <b>2.12.</b> 附属脚本
</a>
</li>
<li class="chapter " data-level="2.13" data-path="chapter2/13_Inheritance.html">
<a href="../chapter2/13_Inheritance.html">
<i class="fa fa-check"></i> <b>2.13.</b> 继承
</a>
</li>
<li class="chapter " data-level="2.14" data-path="chapter2/14_Initialization.html">
<a href="../chapter2/14_Initialization.html">
<i class="fa fa-check"></i> <b>2.14.</b> 构造过程
</a>
</li>
<li class="chapter " data-level="2.15" data-path="chapter2/15_Deinitialization.html">
<a href="../chapter2/15_Deinitialization.html">
<i class="fa fa-check"></i> <b>2.15.</b> 析构过程
</a>
</li>
<li class="chapter " data-level="2.16" data-path="chapter2/16_Automatic_Reference_Counting.html">
<a href="../chapter2/16_Automatic_Reference_Counting.html">
<i class="fa fa-check"></i> <b>2.16.</b> 自动引用计数
</a>
</li>
<li class="chapter " data-level="2.17" data-path="chapter2/17_Optional_Chaining.html">
<a href="../chapter2/17_Optional_Chaining.html">
<i class="fa fa-check"></i> <b>2.17.</b> 可选链
</a>
</li>
<li class="chapter " data-level="2.18" data-path="chapter2/18_Type_Casting.html">
<a href="../chapter2/18_Type_Casting.html">
<i class="fa fa-check"></i> <b>2.18.</b> 类型检查
</a>
</li>
<li class="chapter " data-level="2.19" data-path="chapter2/19_Nested_Types.html">
<a href="../chapter2/19_Nested_Types.html">
<i class="fa fa-check"></i> <b>2.19.</b> 嵌套类型
</a>
</li>
<li class="chapter " data-level="2.20" data-path="chapter2/20_Extensions.html">
<a href="../chapter2/20_Extensions.html">
<i class="fa fa-check"></i> <b>2.20.</b> 扩展
</a>
</li>
<li class="chapter " data-level="2.21" data-path="chapter2/21_Protocols.html">
<a href="../chapter2/21_Protocols.html">
<i class="fa fa-check"></i> <b>2.21.</b> 协议
</a>
</li>
<li class="chapter " data-level="2.22" data-path="chapter2/22_Generics.html">
<a href="../chapter2/22_Generics.html">
<i class="fa fa-check"></i> <b>2.22.</b> 泛型
</a>
</li>
<li class="chapter " data-level="2.23" data-path="chapter2/23_Advanced_Operators.html">
<a href="../chapter2/23_Advanced_Operators.html">
<i class="fa fa-check"></i> <b>2.23.</b> 高级操作符
</a>
</li>
</ul>
</li>
<li class="chapter " data-level="3" data-path="chapter3/chapter3.html">
<a href="../chapter3/chapter3.html">
<i class="fa fa-check"></i> <b>3.</b> 语言参考
</a>
<ul class="articles">
<li class="chapter " data-level="3.1" data-path="chapter3/01_About_the_Language_Reference.html">
<a href="../chapter3/01_About_the_Language_Reference.html">
<i class="fa fa-check"></i> <b>3.1.</b> 关于语言参考
</a>
</li>
<li class="chapter " data-level="3.2" data-path="chapter3/02_Lexical_Structure.html">
<a href="../chapter3/02_Lexical_Structure.html">
<i class="fa fa-check"></i> <b>3.2.</b> 词法结构
</a>
</li>
<li class="chapter " data-level="3.3" data-path="chapter3/03_Types.html">
<a href="../chapter3/03_Types.html">
<i class="fa fa-check"></i> <b>3.3.</b> 类型
</a>
</li>
<li class="chapter " data-level="3.4" data-path="chapter3/04_Expressions.html">
<a href="../chapter3/04_Expressions.html">
<i class="fa fa-check"></i> <b>3.4.</b> 表达式
</a>
</li>
<li class="chapter " data-level="3.5" data-path="chapter3/10_Statements.html">
<a href="../chapter3/10_Statements.html">
<i class="fa fa-check"></i> <b>3.5.</b> 语句
</a>
</li>
<li class="chapter " data-level="3.6" data-path="chapter3/05_Declarations.html">
<a href="../chapter3/05_Declarations.html">
<i class="fa fa-check"></i> <b>3.6.</b> 声明
</a>
</li>
<li class="chapter " data-level="3.7" data-path="chapter3/06_Attributes.html">
<a href="../chapter3/06_Attributes.html">
<i class="fa fa-check"></i> <b>3.7.</b> 特性
</a>
</li>
<li class="chapter " data-level="3.8" data-path="chapter3/07_Patterns.html">
<a href="../chapter3/07_Patterns.html">
<i class="fa fa-check"></i> <b>3.8.</b> 模式
</a>
</li>
<li class="chapter " data-level="3.9" data-path="chapter3/08_Generic_Parameters_and_Arguments.html">
<a href="../chapter3/08_Generic_Parameters_and_Arguments.html">
<i class="fa fa-check"></i> <b>3.9.</b> 泛型参数
</a>
</li>
<li class="chapter " data-level="3.10" data-path="chapter3/09_Summary_of_the_Grammar.html">
<a href="../chapter3/09_Summary_of_the_Grammar.html">
<i class="fa fa-check"></i> <b>3.10.</b> 语法总结
</a>
</li>
</ul>
</li>
<li class="divider"></li>
<li>
<a href="http://www.gitbook.io/" target="blank" class="gitbook-link">Generated using GitBook</a>
</li>
<li style="margin-left:15%;"> <iframe src="http://ghbtns.com/github-btn.html?user=numbbbbb&repo=the-swift-programming-language-in-chinese&type=watch&count=true&size=large"
allowtransparency="true" frameborder="0" scrolling="0" width="170" height="30"></iframe></li>
</ul>
</div>
<div class="book-body">
<div class="body-inner">
<div class="page-wrapper" tabindex="-1">
<div class="book-progress">
<div class="bar">
<div class="inner" style="width: 52.63157894736842%;min-width: 50%;"></div>
</div>
<div class="chapters">
<a href="../index.html" title="Introduction" class="chapter done new-chapter" data-progress="0" style="left: 0%;"></a>
<a href="../chapter1/chapter1.html" title="欢迎使用 Swift" class="chapter done new-chapter" data-progress="1" style="left: 2.6315789473684212%;"></a>
<a href="../chapter1/01_swift.html" title="关于 Swift" class="chapter done " data-progress="1.1" style="left: 5.2631578947368425%;"></a>
<a href="../chapter1/02_a_swift_tour.html" title="Swift 初见" class="chapter done " data-progress="1.2" style="left: 7.894736842105263%;"></a>
<a href="../chapter2/chapter2.html" title="Swift 教程" class="chapter done new-chapter" data-progress="2" style="left: 10.526315789473685%;"></a>
<a href="../chapter2/01_The_Basics.html" title="基础部分" class="chapter done " data-progress="2.1" style="left: 13.157894736842104%;"></a>
<a href="../chapter2/10_Properties.html" title="属性" class="chapter done " data-progress="2.10" style="left: 15.789473684210526%;"></a>
<a href="../chapter2/11_Methods.html" title="方法" class="chapter done " data-progress="2.11" style="left: 18.42105263157895%;"></a>
<a href="../chapter2/12_Subscripts.html" title="附属脚本" class="chapter done " data-progress="2.12" style="left: 21.05263157894737%;"></a>
<a href="../chapter2/13_Inheritance.html" title="继承" class="chapter done " data-progress="2.13" style="left: 23.68421052631579%;"></a>
<a href="../chapter2/14_Initialization.html" title="构造过程" class="chapter done " data-progress="2.14" style="left: 26.31578947368421%;"></a>
<a href="../chapter2/15_Deinitialization.html" title="析构过程" class="chapter done " data-progress="2.15" style="left: 28.94736842105263%;"></a>
<a href="../chapter2/16_Automatic_Reference_Counting.html" title="自动引用计数" class="chapter done " data-progress="2.16" style="left: 31.57894736842105%;"></a>
<a href="../chapter2/17_Optional_Chaining.html" title="可选链" class="chapter done " data-progress="2.17" style="left: 34.21052631578947%;"></a>
<a href="../chapter2/18_Type_Casting.html" title="类型检查" class="chapter done " data-progress="2.18" style="left: 36.8421052631579%;"></a>
<a href="../chapter2/19_Nested_Types.html" title="嵌套类型" class="chapter done " data-progress="2.19" style="left: 39.473684210526315%;"></a>
<a href="../chapter2/02_Basic_Operators.html" title="基本运算符" class="chapter done " data-progress="2.2" style="left: 42.10526315789474%;"></a>
<a href="../chapter2/20_Extensions.html" title="扩展" class="chapter done " data-progress="2.20" style="left: 44.73684210526316%;"></a>
<a href="../chapter2/21_Protocols.html" title="协议" class="chapter done " data-progress="2.21" style="left: 47.36842105263158%;"></a>
<a href="../chapter2/22_Generics.html" title="泛型" class="chapter done " data-progress="2.22" style="left: 50%;"></a>
<a href="../chapter2/23_Advanced_Operators.html" title="高级操作符" class="chapter done " data-progress="2.23" style="left: 52.63157894736842%;"></a>
<a href="../chapter2/03_Strings_and_Characters.html" title="字符串和字符" class="chapter " data-progress="2.3" style="left: 55.26315789473684%;"></a>
<a href="../chapter2/04_Collection_Types.html" title="集合类型" class="chapter " data-progress="2.4" style="left: 57.89473684210526%;"></a>
<a href="../chapter2/05_Control_Flow.html" title="控制流" class="chapter " data-progress="2.5" style="left: 60.526315789473685%;"></a>
<a href="../chapter2/06_Functions.html" title="函数" class="chapter " data-progress="2.6" style="left: 63.1578947368421%;"></a>
<a href="../chapter2/07_Closures.html" title="闭包" class="chapter " data-progress="2.7" style="left: 65.78947368421052%;"></a>
<a href="../chapter2/08_Enumerations.html" title="枚举" class="chapter " data-progress="2.8" style="left: 68.42105263157895%;"></a>
<a href="../chapter2/09_Classes_and_Structures.html" title="类和结构体" class="chapter " data-progress="2.9" style="left: 71.05263157894737%;"></a>
<a href="../chapter3/chapter3.html" title="语言参考" class="chapter new-chapter" data-progress="3" style="left: 73.6842105263158%;"></a>
<a href="../chapter3/01_About_the_Language_Reference.html" title="关于语言参考" class="chapter " data-progress="3.1" style="left: 76.3157894736842%;"></a>
<a href="../chapter3/09_Summary_of_the_Grammar.html" title="语法总结" class="chapter " data-progress="3.10" style="left: 78.94736842105263%;"></a>
<a href="../chapter3/02_Lexical_Structure.html" title="词法结构" class="chapter " data-progress="3.2" style="left: 81.57894736842105%;"></a>
<a href="../chapter3/03_Types.html" title="类型" class="chapter " data-progress="3.3" style="left: 84.21052631578948%;"></a>
<a href="../chapter3/04_Expressions.html" title="表达式" class="chapter " data-progress="3.4" style="left: 86.84210526315789%;"></a>
<a href="../chapter3/10_Statements.html" title="语句" class="chapter " data-progress="3.5" style="left: 89.47368421052632%;"></a>
<a href="../chapter3/05_Declarations.html" title="声明" class="chapter " data-progress="3.6" style="left: 92.10526315789474%;"></a>
<a href="../chapter3/06_Attributes.html" title="特性" class="chapter " data-progress="3.7" style="left: 94.73684210526316%;"></a>
<a href="../chapter3/07_Patterns.html" title="模式" class="chapter " data-progress="3.8" style="left: 97.36842105263158%;"></a>
<a href="../chapter3/08_Generic_Parameters_and_Arguments.html" title="泛型参数" class="chapter " data-progress="3.9" style="left: 100%;"></a>
</div>
</div>
<div class="page-inner">
<section class="normal" id="section-gitbook_167">
<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>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 Swifts second set of arithmetic operators that overflow by default, such as the overflow addition operator (&amp;+). All of these overflow operators begin with an ampersand (&amp;).</p>
<p>不同于C语言中的数值计算, Swift的数值计算默认是不可溢出的. 溢出行为会被捕获并报告为错误. 你是故意的? 好吧, 你可以使用Swift为你准备的另一套默认允许溢出的数值运算符, 如可溢出加 <code>&amp;+</code>. 所有允许溢出的运算符都是以 <code>&amp;</code> 开始的.</p>
<p>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.</p>
<p>自定义的结构, 类和枚举, 是否可以使用标准的运算符来定义操作? 当然可以, 在Swift中, 你可以对你创建的类型定制运算符的行为.</p>
<p>Youre 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.</p>
<p>可定制的运算符并不限于那些预设的运算符, 也创建个性的中置, 前置,后置,还有赋值运算符, 当然优先级和结合性也是可以自定义的. 这些运算符的实现可以使用预设的运算符, 也可以使用已定制好的运算符.</p>
<h1 id="bitwise-operators">Bitwise Operators</h1>
<h1 id="-">位运算符</h1>
<p>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.</p>
<p>位操作符通常在诸如图像处理和创建设备驱动等底层开发中使用, 使用它可以操作数据结构中原始数据中的个别比特. 当然, 使用一个自定的协议进行通信的时候, 使用位运算符来对原始数据进行编码和解码也是非常有效的.</p>
<p>Swift supports all of the bitwise operators found in C, as described below.</p>
<p>Swift支持所有C语言的位运算符, 如下描述:</p>
<h2 id="bitwise-not-operator">Bitwise NOT Operator</h2>
<h2 id="-">按位取反运算符</h2>
<p>The bitwise NOT operator (~) inverts all bits in a number:</p>
<p>按位取反运算符 <code>~</code> 对一个操作数的每一位都取反.</p>
<p><img src="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Art/bitwiseNOT_2x.png" alt="Art/bitwiseNOT_2x.png" title="Art/bitwiseNOT_2x.png"></p>
<p>The bitwise NOT operator is a prefix operator, and appears immediately before the value it operates on, without any white space:</p>
<p>这个运算符是前置, 所以请不加任何空格地写着操作数之前.</p>
<pre><code>let initialBits: UInt8 = 0b00001111
let invertedBits = ~initialBits // 等于 0b11110000
</code></pre><p>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.</p>
<p><code>UInt8</code> 整型是8位的, 可以储存0~255之间的任意数. 这个例子初始化一个整型为二进制值 <code>00001111</code>(前4位为 <code>0</code>, 后4位为 <code>1</code>), 它的十进制值为 <code>15</code>.</p>
<p>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.</p>
<p>使用按位取反运算 <code>~</code><code>initialBits</code> 操作, 然后赋值给 <code>invertedBits</code> 这个新常量. 这个新常量的值等于所有位都取反的<code>initialBits</code>, 即 <code>1</code> 变成 <code>0</code>, <code>0</code> 变成 <code>1</code>, 变成了 <code>11110000</code>, 十进制值为 <code>240</code>.</p>
<h2 id="bitwise-and-operator">Bitwise AND Operator</h2>
<h2 id="-">按位与运算符</h2>
<p>The bitwise AND operator (&amp;) 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:</p>
<p>按位与运算符对两个数进行操作, 然后返回一个新的数, 这个数的每个位都需两个输入数的同一位都为1的时候才为1.</p>
<p><img src="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Art/bitwiseAND_2x.png" alt="Art/bitwiseAND_2x.png" title="Art/bitwiseAND_2x.png"></p>
<p>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:</p>
<p>如下代码, <code>firstSixBits</code><code>lastSixBits</code> 中间4个位都为1. 对它俩进行按位与运算后, 就得到了 <code>00111100</code>, 即十进制的 <code>60</code>.</p>
<pre><code>let firstSixBits: UInt8 = 0b11111100
let lastSixBits: UInt8 = 0b00111111
let middleFourBits = firstSixBits &amp; lastSixBits // 等于 00111100
</code></pre><h2 id="bitwise-or-operator">Bitwise OR Operator</h2>
<h2 id="-">按位或运算</h2>
<p>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:</p>
<p>按位或运算符 <code>|</code> 比较两个数, 然后返回一个新的数, 这个数的每一位设置1的条件是两个输入数的同一位都不为0(即任意一个为1, 或都为1).</p>
<p><img src="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Art/bitwiseOR_2x.png" alt="Art/bitwiseOR_2x.png" title="Art/bitwiseOR_2x.png"></p>
<p>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:</p>
<p>如下代码, <code>someBits</code><code>moreBits</code> 在不同位上有 <code>1</code>. 按位或运行的结果是 <code>11111110</code>, 即十进制的 <code>254</code>.</p>
<pre><code>let someBits: UInt8 = 0b10110010
let moreBits: UInt8 = 0b01011110
let combinedbits = someBits | moreBits // 等于 11111110
</code></pre><h2 id="bitwise-xor-operator">Bitwise XOR Operator</h2>
<h2 id="-">按位异或运算符</h2>
<p>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:</p>
<p>按位异或运算符 <code>^</code> 比较两个数, 然后返回一个数, 这个数的每个位设为 <code>1</code>的条件是两个输入数的同一位不同, 如果相同就设为 <code>0</code>.</p>
<p><img src="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Art/bitwiseXOR_2x.png" alt="Art/bitwiseXOR_2x.png" title="Art/bitwiseXOR_2x.png"></p>
<p>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:</p>
<p>以下代码, <code>firstBits</code><code>otherBits</code> 都有一个 <code>1</code> 跟另一个数不同的. 所以按位异或的结果是把它这些位置为 <code>1</code>, 其他都置为 <code>0</code>.</p>
<pre><code>let firstBits: UInt8 = 0b00010100
let otherBits: UInt8 = 0b00000101
let outputBits = firstBits ^ otherBits // 等于 00010001
</code></pre><h2 id="bitwise-left-and-right-shift-operators">Bitwise Left and Right Shift Operators</h2>
<h2 id="-">按位左移/右移运算符</h2>
<p>The bitwise left shift operator (&lt;&lt;) and bitwise right shift operator (&gt;&gt;) move all bits in a number to the left or the right by a certain number of places, according to the rules defined below.</p>
<p>左移运算符 <code>&lt;&lt;</code> 和右移运算符 <code>&gt;&gt;</code> 会把一个数的所有比特位按以下定义的规则向左或向右移动指定位数.</p>
<p>Bitwise left and right shifts have the effect of multiplying or dividing an integer number by a factor of two. Shifting an integers bits to the left by one position doubles its value, whereas shifting it to the right by one position halves its value.</p>
<p>按位左移和按位右移的效果相当把一个整数乘于或除于一个因子为 <code>2</code> 的整数. 向左移动一个整型的比特位相当于把这个数乘于 <code>2</code>, 向右移一位就是除于 <code>2</code>.</p>
<h3 id="shifting-behavior-for-unsigned-integers">Shifting Behavior for Unsigned Integers</h3>
<h3 id="-">对无符整型进行移位</h3>
<p>The bit-shifting behavior for unsigned integers is as follows:
对无符整型的移位的效果如下:</p>
<p>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 integers storage are discarded.
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.</p>
<p>已经存在的比特位向左或向右移动指定的位数. 被移出整型存储边界的的位数直接抛弃, 移动留下的空白位用零 <code>0</code> 来填充. 这种方法称为逻辑移位.</p>
<p>The illustration below shows the results of 11111111 &lt;&lt; 1 (which is 11111111 shifted to the left by 1 place), and 11111111 &gt;&gt; 1 (which is 11111111 shifted to the right by 1 place). Blue numbers are shifted, gray numbers are discarded, and orange zeroes are inserted:</p>
<p>以下这张把展示了 <code>11111111 &lt;&lt; 1</code> (<code>11111111</code> 向左移1位), 和 <code>11111111 &lt;&lt; 1</code> (<code>11111111</code> 向右移1位). 蓝色的是被移位的, 灰色是被抛弃的, 橙色的 <code>0</code> 是被填充进来的.</p>
<p><img src="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Art/bitshiftUnsigned_2x.png" alt="Art/bitshiftUnsigned_2x.png" title="Art/bitshiftUnsigned_2x.png">
Heres how bit shifting looks in Swift code:</p>
<pre><code>let shiftBits: UInt8 = 4 // 即二进制的00000100
shiftBits &lt;&lt; 1 // 00001000
shiftBits &lt;&lt; 2 // 00010000
shiftBits &lt;&lt; 5 // 10000000
shiftBits &lt;&lt; 6 // 00000000
shiftBits &gt;&gt; 2 // 00000001
</code></pre><p>You can use bit shifting to encode and decode values within other data types:
你可以使用移位操作进行其他数据类型的编码和解码.</p>
<pre><code>let pink: UInt32 = 0xCC6699
let redComponent = (pink &amp; 0xFF0000) &gt;&gt; 16 // redComponent 是 0xCC, 即 204
let greenComponent = (pink &amp; 0x00FF00) &gt;&gt; 8 // greenComponent 是 0x66, 即 102
let blueComponent = pink &amp; 0x0000FF // blueComponent 是 0x99, 即 153
</code></pre><p>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 Swifts hexadecimal number representation. This color is then decomposed into its red (CC), green (66), and blue (99) components by the bitwise AND operator (&amp;) and the bitwise right shift operator (&gt;&gt;).</p>
<p>这个例子使用了一个 <code>UInt32</code> 的命名为 <code>pink</code>的常量来储存层叠样式表 <code>CSS</code> 中粉色的颜色值, <code>CSS</code>颜色<code>#CC6699</code>在Swift用十六进制<code>0xCC6699</code>来表示. 然后使用按位与(&amp;)和按位右移就可以从这个颜色值中解析出红(CC), 绿(66), 蓝(99)三个部分.</p>
<p>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.</p>
<p><code>0xCC6699</code><code>0xFF0000</code> 进行按位与 <code>&amp;</code> 操作就可以得到红色部分. <code>0xFF0000</code> 中的 <code>0</code> 了遮盖了 <code>OxCC6699</code> 的第二和第三个字节, 这样 <code>6699</code> 被忽略了, 只留下 <code>0xCC0000</code>.</p>
<p>This number is then shifted 16 places to the right (&gt;&gt; 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.</p>
<p>然后, 按向右移动16位, 即 <code>&gt;&gt; 16</code>. 十六进制中每两个字符是8比特位, 所以移动16位的结果是把 <code>0xCC0000</code> 变成 <code>0x0000CC</code>. 这和 <code>0xCC</code> 是相等的, 都是十进制的 <code>204</code>.</p>
<p>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.</p>
<p>同样的, 绿色部分来自于 <code>0xCC6699</code><code>0x00FF00</code> 的按位操作得到 <code>0x006600</code>. 然后向右移动8們, 得到 <code>0x66</code>, 即十进制的 <code>102</code>.</p>
<p>Finally, the blue component is obtained by performing a bitwise AND between the numbers 0xCC6699 and 0x0000FF, which gives an output value of 0x000099. Theres no need to shift this to the right, as 0x000099 already equals 0x99, which has a decimal value of 153.</p>
<p>最后, 蓝色部分对 <code>0xCC6699</code><code>0x0000FF</code> 进行按位与运算, 得到 <code>0x000099</code>, 无需向右移位了, 所以结果就是 <code>0x99</code>, 即十进制的 <code>153</code>.</p>
<h3 id="shifting-behavior-for-signed-integers">Shifting Behavior for Signed Integers</h3>
<p>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.)</p>
<p>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.</p>
<p>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. Heres how the bits inside an Int8 look for the number 4:</p>
<p><img src="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Art/bitshiftSignedFour_2x.png" alt="Art/bitshiftSignedFour_2x.png" title="Art/bitshiftSignedFour_2x.png">
The sign bit is 0 (meaning “positive”), and the seven value bits are just the number 4, written in binary notation.</p>
<p>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.</p>
<p>Heres how the bits inside an Int8 look for the number -4:</p>
<p><img src="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Art/bitshiftSignedMinusFour_2x.png" alt="Art/bitshiftSignedMinusFour_2x.png" title="Art/bitshiftSignedMinusFour_2x.png">
This time, the sign bit is 1 (meaning “negative”), and the seven value bits have a binary value of 124 (which is 128 - 4):</p>
<p><img src="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Art/bitshiftSignedMinusFourValue_2x.png" alt="Art/bitshiftSignedMinusFourValue_2x.png" title="Art/bitshiftSignedMinusFourValue_2x.png">
The encoding for negative numbers is known as a twos complement representation. It may seem an unusual way to represent negative numbers, but it has several advantages.</p>
<p>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 doesnt fit in the eight bits once youre done:</p>
<p><img src="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Art/bitshiftSignedAddition_2x.png" alt="Art/bitshiftSignedAddition_2x.png" title="Art/bitshiftSignedAddition_2x.png">
Second, the twos 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:</p>
<p>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.
<img src="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Art/bitshiftSigned_2x.png" alt="Art/bitshiftSigned_2x.png" title="Art/bitshiftSigned_2x.png">
This action ensures that signed integers have the same sign after they are shifted to the right, and is known as an arithmetic shift.</p>
<p>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.</p>
<h1 id="overflow-operators">Overflow Operators</h1>
<p>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.</p>
<p>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:</p>
<pre><code>var potentialOverflow = Int16.max
// potentialOverflow equals 32767, which is the largest value an Int16 can hold
potentialOverflow += 1
// this causes an error
</code></pre><p>Providing error handling when values get too large or too small gives you much more flexibility when coding for boundary value conditions.</p>
<p>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 (&amp;):</p>
<ul>
<li>Overflow addition (&amp;+)</li>
<li>Overflow subtraction (&amp;-)</li>
<li>Overflow multiplication (&amp;*)</li>
<li>Overflow division (&amp;/)</li>
<li>Overflow remainder (&amp;%)</li>
</ul>
<h2 id="value-overflow">Value Overflow</h2>
<p>Heres an example of what happens when an unsigned value is allowed to overflow, using the overflow addition operator (&amp;+):</p>
<pre><code>var willOverflow = UInt8.max
// willOverflow equals 255, which is the largest value a UInt8 can hold
willOverflow = willOverflow &amp;+ 1
// willOverflow is now equal to 0
</code></pre><p>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 (&amp;+). 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:</p>
<p><img src="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Art/overflowAddition_2x.png" alt="Art/overflowAddition_2x.png" title="Art/overflowAddition_2x.png">
Value Underflow</p>
<p>Numbers can also become too small to fit in their types maximum bounds. Heres an example.</p>
<p>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:</p>
<p><img src="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Art/overflowUnsignedSubtraction_2x.png" alt="Art/overflowUnsignedSubtraction_2x.png" title="Art/overflowUnsignedSubtraction_2x.png">
Heres how that looks in Swift code:</p>
<pre><code>var willUnderflow = UInt8.min
// willUnderflow equals 0, which is the smallest value a UInt8 can hold
willUnderflow = willUnderflow &amp;- 1
// willUnderflow is now equal to 255
</code></pre><p>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:</p>
<p><img src="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Art/overflowSignedSubtraction_2x.png" alt="Art/overflowSignedSubtraction_2x.png" title="Art/overflowSignedSubtraction_2x.png"></p>
<p>Heres the same thing in Swift code:</p>
<pre><code>var signedUnderflow = Int8.min
// signedUnderflow equals -128, which is the smallest value an Int8 can hold
signedUnderflow = signedUnderflow &amp;- 1
// signedUnderflow is now equal to 127
</code></pre><p>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.</p>
<h2 id="division-by-zero">Division by Zero</h2>
<p>Dividing a number by zero (i / 0), or trying to calculate remainder by zero (i % 0), causes an error:</p>
<pre><code>let x = 1
let y = x / 0
</code></pre><p>However, the overflow versions of these operators (&amp;/ and &amp;%) return a value of zero if you divide by zero:</p>
<pre><code>let x = 1
let y = x &amp;/ 0
// y is equal to 0
</code></pre><h1 id="precedence-and-associativity">Precedence and Associativity</h1>
<p>Operator precedence gives some operators higher priority than others; these operators are calculated first.</p>
<p>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.”</p>
<p>It is important to consider each operators precedence and associativity when working out the order in which a compound expression will be calculated. Heres an example. Why does the following expression equal 4?</p>
<pre><code>2 + 3 * 4 % 5
// this equals 4
</code></pre><p>Taken strictly from left to right, you might expect this to read as follows:</p>
<p>2 plus 3 equals 5;
5 times 4 equals 20;
20 remainder 5 equals 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.</p>
<p>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:</p>
<pre><code>2 + ((3 * 4) % 5)
</code></pre><p>(3 * 4) is 12, so this is equivalent to:</p>
<pre><code>2 + (12 % 5)
</code></pre><p>(12 % 5) is 2, so this is equivalent to:</p>
<pre><code>2 + 2
</code></pre><p>This calculation yields the final answer of 4.</p>
<p>For a complete list of Swift operator precedences and associativity rules, see Expressions.</p>
<blockquote>
<p>NOTE</p>
<p>Swifts 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.</p>
</blockquote>
<p>Operator Functions</p>
<p>Classes and structures can provide their own implementations of existing operators. This is known as overloading the existing operators.</p>
<p>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.</p>
<p>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:</p>
<p>struct Vector2D {
var x = 0.0, y = 0.0
}
@infix func + (left: Vector2D, right: Vector2D) -&gt; Vector2D {
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.</p>
<p>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.</p>
<p>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:</p>
<p>let vector = Vector2D(x: 3.0, y: 1.0)
let anotherVector = Vector2D(x: 2.0, y: 4.0)
let combinedVector = vector + anotherVector
// combinedVector is a Vector2D instance with values of (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.</p>
<p><img src="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Art/vectorAddition_2x.png" alt="Art/vectorAddition_2x.png" title="Art/vectorAddition_2x.png">
Prefix and Postfix Operators</p>
<p>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++).</p>
<p>You implement a prefix or postfix unary operator by writing the @prefix or @postfix attribute before the func keyword when declaring the operator function:</p>
<p>@prefix func - (vector: Vector2D) -&gt; Vector2D {
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.</p>
<p>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:</p>
<p>let positive = Vector2D(x: 3.0, y: 4.0)
let negative = -positive
// negative is a Vector2D instance with values of (-3.0, -4.0)
let alsoPositive = -negative
// alsoPositive is a Vector2D instance with values of (3.0, 4.0)
Compound Assignment Operators</p>
<p>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 operators left input parameter as inout, because the parameters value will be modified directly from within the operator function.</p>
<p>The example below implements an addition assignment operator function for Vector2D instances:</p>
<p>@assignment func += (inout left: Vector2D, right: Vector2D) {
left = left + right
}
Because an addition operator was defined earlier, you dont 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:</p>
<p>var original = Vector2D(x: 1.0, y: 2.0)
let vectorToAdd = Vector2D(x: 3.0, y: 4.0)
original += vectorToAdd
// original now has values of (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:</p>
<p>@prefix @assignment func ++ (inout vector: Vector2D) -&gt; Vector2D {
vector += Vector2D(x: 1.0, y: 1.0)
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:</p>
<p>var toIncrement = Vector2D(x: 3.0, y: 4.0)
let afterIncrement = ++toIncrement
// toIncrement now has values of (4.0, 5.0)
// afterIncrement also has values of (4.0, 5.0)
NOTE</p>
<p>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.</p>
<p>Equivalence Operators</p>
<p>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.</p>
<p>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:</p>
<p>@infix func == (left: Vector2D, right: Vector2D) -&gt; Bool {
return (left.x == right.x) &amp;&amp; (left.y == right.y)
}
@infix func != (left: Vector2D, right: Vector2D) -&gt; Bool {
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.</p>
<p>You can now use these operators to check whether two Vector2D instances are equivalent:</p>
<p>let twoThree = Vector2D(x: 2.0, y: 3.0)
let anotherTwoThree = Vector2D(x: 2.0, y: 3.0)
if twoThree == anotherTwoThree {
println(&quot;These two vectors are equivalent.&quot;)
}
// prints &quot;These two vectors are equivalent.&quot;
Custom Operators</p>
<p>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 / = - + * % &lt; &gt; ! &amp; | ^ . ~.</p>
<p>New operators are declared at a global level using the operator keyword, and can be declared as prefix, infix or postfix:</p>
<p>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:</p>
<p>@prefix @assignment func +++ (inout vector: Vector2D) -&gt; Vector2D {
vector += 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):</p>
<p>var toBeDoubled = Vector2D(x: 1.0, y: 4.0)
let afterDoubling = +++toBeDoubled
// toBeDoubled now has values of (2.0, 8.0)
// afterDoubling also has values of (2.0, 8.0)
Precedence and Associativity for Custom Infix Operators</p>
<p>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 operators interaction with other infix operators.</p>
<p>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.</p>
<p>The associativity value defaults to none if it is not specified. The precedence value defaults to 100 if it is not specified.</p>
<p>The following example defines a new custom infix operator called +-, with left associativity and a precedence of 140:</p>
<p>operator infix +- { associativity left precedence 140 }
func +- (left: Vector2D, right: Vector2D) -&gt; Vector2D {
return Vector2D(x: left.x + right.x, y: left.y - right.y)
}
let firstVector = Vector2D(x: 1.0, y: 2.0)
let secondVector = Vector2D(x: 3.0, y: 4.0)
let plusMinusVector = firstVector +- secondVector
// plusMinusVector is a Vector2D instance with values of (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.</p>
</section>
</div>
</div>
</div>
<a href="../chapter2/22_Generics.html" class="navigation navigation-prev " aria-label="Previous page: 泛型"><i class="fa fa-angle-left"></i></a>
<a href="../chapter3/chapter3.html" class="navigation navigation-next " aria-label="Next page: 语言参考"><i class="fa fa-angle-right"></i></a>
</div>
</div>
<script src="http://cdn.bootcss.com/ace/1.1.3/ace.js"></script>
<script src="http://cdn.bootcss.com/ace/1.1.3/mode-javascript.js"></script>
<script src="../gitbook/jsrepl/jsrepl.js" id="jsrepl-script"></script>
<script src="../gitbook/app.js"></script>
<script src="../gitbook/plugins/gitbook-plugin-mixpanel/plugin.js"></script>
<script src="http://cdn.mathjax.org/mathjax/2.0-latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script src="../gitbook/plugins/gitbook-plugin-mathjax/plugin.js"></script>
<script>
require(["gitbook"], function(gitbook) {
var config = {};
gitbook.start(config);
});
</script>
</body>
</html>