## 按位運算符
### ~
1變0,0變1。

~~~
let initialBits: UInt8 = 0b00001111
let invertedBits = ~initialBits // equals 11110000
~~~
### $
全1得1,其他為0

~~~
let firstSixBits: UInt8 = 0b11111100
let lastSixBits: UInt8 = 0b00111111
let middleFourBits = firstSixBits & lastSixBits // equals 00111100
~~~
### |
有1得1,其他為0

~~~
let someBits: UInt8 = 0b10110010
let moreBits: UInt8 = 0b01011110
let combinedbits = someBits | moreBits // equals 11111110
~~~
### ^
相異為1,相同為0

~~~
let firstBits: UInt8 = 0b00010100
let otherBits: UInt8 = 0b00000101
let outputBits = firstBits ^ otherBits // equals 00010001
~~~
### <<和>>
<<整體左移,右邊填0;
>> 整體右移,左邊填0。

~~~
let shiftBits: UInt8 = 4 // 00000100 in binary
shiftBits << 1 // 00001000
shiftBits << 2 // 00010000
shiftBits << 5 // 10000000
shiftBits << 6 // 00000000
shiftBits >> 2 // 00000001
~~~
## 算子函數
上面講解的都是簡單的運算符,下面的是為對象添加運算符,使之可計算。
### 符號在中間
~~~
struct Vector2D {
var x = 0.0, y = 0.0
}
func + (left: Vector2D, right: Vector2D) -> Vector2D {
return Vector2D(x: left.x + right.x, y: left.y + right.y)
}
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)
~~~
### 前綴和后綴
前綴關鍵字prefix
后綴關鍵字postfix
~~~
prefix func - (vector: Vector2D) -> Vector2D {
return Vector2D(x: -vector.x, y: -vector.y)
}
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)
~~~
### 復合賦值運算符
這里用+=舉例。
~~~
func += (inout left: Vector2D, right: Vector2D) {
left = left + right
}
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)
~~~
## 其他
### 參考資料
[The Swift Programming Language (Swift 2.1)](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html)
### 文檔修改記錄
| 時間 | 描述 |
|-----|-----|
| 2015-11-1 | 根據 [The Swift Programming Language (Swift 2.1)](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html)中的Classes and Structures總結 |
版權所有:[http://blog.csdn.net/y550918116j](http://blog.csdn.net/y550918116j)
- 前言
- Swift函數
- Swift閉包(Closures)
- Swift枚舉(Enumerations)
- Swift類和結構體(Classes and Structures)
- Swift屬性(Properties)
- Swift方法(Methods)
- Swift下標(Subscripts)
- Swift繼承(Inheritance)
- Swift初始化(Initialization)
- Swift銷毀(Deinitialization)
- Swift可選鏈(Optional Chaining)
- Swift錯誤處理(Error Handling)
- Swift類型選擇(Type Casting)
- Swift協議(Protocols)
- Swift訪問控制(Access Control)
- Swift高級運算符(Advanced Operators)