Swift中的那些運算符

接觸 Swift 已經一年了,可是公司的項目還是不能用 Swift 來寫。最近組長讓我整理一些 Swift 的東西,做個內部分享,這是第一篇(以 2015年7月21 Swift2.0 版本為準)。

Swift 的操作運算符也是分為:一元、二元、三元。

一元 二元 三元
+(正)-(負) !(非) ++(自增) --(自減) 算數運算符:+,-,*,/, % 復合運算符:+=, -=, *=, /=, %= a > b ? a : b
賦值運算符:
let b = 10
var a = 5
a = b
// a is now equal to 10

和C語言不同的是:Swift 的賦值運算不會有返回值。比如:

let (x, y) = (1, 2) //聲明一個元組
// x is equal to 1, and y is equal to 2

if x = y {
    //這里會報錯,因為 y 賦值給 x 不會有返回值,在 C 語言中,因為有返回值,可以判斷 x 是否為空,這里也體現了 Swift 語言的安全性
}
算數運算符:
1 + 2       // equals 3
5 - 3       // equals 2
2 * 3       // equals 6
10.0 / 2.5  // equals 4.0
求余運算符:
8 % 2.5     // equals 0.5  (注:和 C 語言不同的是 Swift 可以對浮點數進行求余)
對浮點數求余示意圖
自增、自減運算符:
++, -- (與 C 語言相同,不解釋)
一元加減操作符:

就是數學中的正負,不解釋。

let three = 3
let minusThree = -three       // minusThree equals -3
let plusThree = -minusThree   // plusThree equals 3, or "minus minus three"
let minusSix = -6
let alsoMinusSix = +minusSix  // alsoMinusSix equals -6
復合運算符:
+=, -=,  *=,  /=,  %= (不解釋)
比較運算符:
1 == 1   // true, because 1 is equal to 1
2 != 1   // true, because 2 is not equal to 1
2 > 1    // true, because 2 is greater than 1
1 < 2    // true, because 1 is less than 2
1 >= 1   // true, because 1 is greater than or equal to 1
2 <= 1   // false, because 2 is not less than or equal to 1

使用例子:

let name = "world"
if name == "world" {
    print("hello, world")
} else {
    print("I'm sorry \(name), but I don't recognize you")
}
// prints "hello, world", because name is indeed equal to "world"

===!==恒等運算符:

    let view1: UIView = UIView()
    view1.backgroundColor = UIColor.redColor()
    let view2 = view1
    view2.backgroundColor = UIColor.blackColor()
    if view1 === view2 {
        print("view1 恒等于 view2")
    }
Xcode控制臺輸出

恒等于和恒不等于比較的是內存地址。改變 view1 和 view2 的背景色并不改變內存地址,所以 view1 恒等于 view2。恒不等就不再解釋。

三元運算符:

跟 C 語言一樣, 不解釋。

let contentHeight = 40
let hasHeader = true
let rowHeight = contentHeight + (hasHeader ? 50 : 20)
// rowHeight is equal to 90

等同于:

let contentHeight = 40
let hasHeader = true
var rowHeight = contentHeight
if hasHeader {
    rowHeight = rowHeight + 50
} else {
    rowHeight = rowHeight + 20
}
// rowHeight is equal to 90
可選值聯合運算符:
let defaultColorName = "red"
var userDefinedColorName: String?   // defaults to nil

var colorNameToUse = userDefinedColorName ?? defaultColorName
// userDefinedColorName is nil, so colorNameToUse is set to the default of "red"

userDefinedColorName = "green"
colorNameToUse = userDefinedColorName ?? defaultColorName

??操作符,先對可選值進行拆包,如果不為 nil 返回操作符前面的值,如果為空返回后者。

a ?? b 等價于 a != nil ? a! : b
范圍運算符:
1...5 是 1,2,3,4,5
1..<5 是 1,2,3,4
邏輯運算符:

與 C 語言的一樣。

非:

let allowedEntry = false
if !allowedEntry {
    print("ACCESS DENIED")
 }
 // prints "ACCESS DENIED"

與:

let enteredDoorCode = true
let passedRetinaScan = false
if enteredDoorCode && passedRetinaScan {
    print("Welcome!")
} else {
    print("ACCESS DENIED")
}
// prints "ACCESS DENIED"

或:

let hasDoorKey = false
let knowsOverridePassword = true
if hasDoorKey || knowsOverridePassword {
    print("Welcome!")
} else {
    print("ACCESS DENIED")
}
// prints "Welcome!"
高級操作:

按位操作符(~):

let initialBits: UInt8 = 0b00001111
let invertedBits = ~initialBits  // equals 11110000
按位操作示意圖

按位操作符就是對二進制的 0 和 1 進行取反,1變0,0變1.

按位與操作符(&):

let firstSixBits: UInt8 = 0b11111100
let lastSixBits: UInt8  = 0b00111111
let middleFourBits = firstSixBits & lastSixBits  // equals 00111100
按位與操作符

按位或操作符(|):

let someBits: UInt8 = 0b10110010
let moreBits: UInt8 = 0b01011110
let combinedbits = someBits | moreBits  // equals 11111110
按位或操作符示意圖

按位異或操作符(^):

let firstBits: UInt8 = 0b00010100
let otherBits: UInt8 = 0b00000101
let outputBits = firstBits ^ otherBits  // equals 00010001
按位異或操作符示意圖

按位左移或右移運算符(<<、<<):
和C語言一樣,不解釋。

重載操作運算符:

Swift 運算符可以對基本數據類型和進行操作,是不能對結構體進行操作的,如果想讓結構體也能使用運算符進行操作,可以重載運算符。

 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 or 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)

重載自增運算符:

prefix func ++ (inout vector: Vector2D) -> Vector2D {
    vector += Vector2D(x: 1.0, y: 1.0)
    return vector
}

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)

注意:賦值運算符=和三元運算符 a ? b : c不能被重載。

重載==運算符:

func == (left: Vector2D, right: Vector2D) -> Bool {
    return (left.x == right.x) && (left.y == right.y)
}
func != (left: Vector2D, right: Vector2D) -> Bool {
    return !(left == right)
}

let twoThree = Vector2D(x: 2.0, y: 3.0)
let anotherTwoThree = Vector2D(x: 2.0, y: 3.0)
if twoThree == anotherTwoThree {
    print("These two vectors are equivalent.")
}
// prints "These two vectors are equivalent."

自定義運算符:

是的,你沒看錯,Swift可以自定義運算符。自定義的運算符可以在全局使用。需要使用operator關鍵字。使用prefix, infix or postfix標記運算符使用的位置。

prefix operator +++ {}
prefix func +++ (inout vector: Vector2D) -> Vector2D {
    vector += vector
    return vector
}

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)

自定義操作符,可以定義操作符的關聯性associativity和優先級precedenceassociativity有三個值:left, right, none,默認是noneprecedence默認值是:100

infix operator +- { associativity left precedence 140 }
func +- (left: Vector2D, right: Vector2D) -> 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)

好了,下篇見~

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容