C++Swift中的那个运算符

接触 斯威夫特 已经一年了,不过公司的项目照旧无法用 Swift来写。目前CEO让本人收拾一些 Swift 的事物,做个里头分享,那是率先篇(以
贰零壹伍年十一月21 斯维夫特2.0 版本为准)。

斯维夫特 的操作运算符也是分为:一元、二元、长富。

一元 二元 三元
+(正)-(负) !(非) ++(自增) --(自减) 算数运算符:+,-,*,/, % 复合运算符:+=, -=, *=, /=, %= 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

C++,按位与操作符

按位或操作符(|):

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)

好了,下篇见~