SwiftSwiftios学习

Swift中的那些运算符

2015-07-28  本文已影响4017人  碧霄问鼎

接触 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)

好了,下篇见~

上一篇下一篇

猜你喜欢

热点阅读