Swift运算符如何使用方法浅析

溢出运算符(Overflow Operator) 1、Swift的算数运算符出现溢出时会抛出运行时错误 var v: UInt8 = UInt8 min v -

溢出运算符(Overflow Operator)

1、Swift的算数运算符出现溢出时会抛出运行时错误

var v: UInt8 = UInt8.min
v -= 1

2、Swift有溢出运算符(&+、&-、&*),用来支持溢出运算

var v1 = UInt8.min
var v2 = v1 &- 1 //v2 = 255
var v1 = UInt8.max
var v2 = v1 &* 2 // 等价于 v1 &+ v1

运算符重载(Operator Overload)

1、类、结构体、枚举可以为现有的运算符提供自定义的实现,这个操作叫做:运算符重载

struct Point {
    var x = 0, y = 0
    static func + (p1: Point, p2: Point) -> Point {
        Point(x: p1.x + p2.x, y: p1.y + p2.y)
    }
    static prefix func - (p: Point) -> Point {
        Point(x: -p.x, y: -p.y)
    }
    static func += (p1: inout Point, p2: Point) {
        p1 = p1 + p2
    }
    static postfix func ++ (p: inout Point) -> Point {
        let tmp = p
        p += Point(x: 1, y: 1)
        return tmp
    }
    static prefix func ++ (p: inout Point) -> Point {
        p += Point(x: 1, y: 1)
        return p
    }
}
var p1 = Point(x: 10, y: 20)
var p2 = Point(x: 11, y: 22)
let p3 = p1 + p2
let p4 = -p3
print(p4)

Equatable

1、要想得知2个实例是否等价,一般做法是遵守Equatable协议,重载 == 运算符

与此同时,等价于重载了 != 运算符

class Person: Equatable {
    var age: Int
    init(age: Int) {
        self.age = age
    }
    static func == (lhs: Person, rhs: Person) -> Bool {
        lhs.age == rhs.age
    }
}
var p1 = Person.init(age: 10)
var p2 = Person(age: 11)
print(p1 == p2)

2、Swift为以下类型提供默认的Equatable实现

没有关联类型的枚举

只拥有遵守Equatable协议关联类型的枚举

只拥有遵守Equatable协议存储属性的结构体

enum Answer {
    case wrong
    case right
}
var s1 = Answer.wrong
var s2 = Answer.right
print(s1 == s2)

3、引用类型比较存储的地址值是否相等(是否引用着同一个对象),使用恒等运算符 === 、!==

Comparable

1、要想比较2个实例的大小,一般做法是:遵守Comparable协议,重载相应的运算符

自定义运算符 (Custom Operator)

1、可以自定义新的运算符:在全局作用域使用operator进行声明

prefix operator 前缀运算符
postfix operator 后缀运算符
infix operator 中缀运算符:优先级组

precedencegroup 优先级组 {
    associativity: 结合性(left/right/none)
    higherThan: 比谁的优先级高
    lowerThan: 比谁的优先级低
    assignment: true代表在可选链操作中拥有跟赋值运算符一样的优先级
}
prefix operator +++
prefix func +++ (_ i: inout Int) {
    i += 2
}
var age = 10
+++age
infix operator +-: PlusMinusPrecedence
precedencegroup PlusMinusPrecedence {
    associativity: none
    higherThan: AdditionPrecedence
    lowerThan: MultiplicationPrecedence
    assignment: true
}
struct Point {
    var x = 0, y = 0
 
    static func +- (p1: Point, p2: Point) -> Point {
        Point(x: p1.x + p2.x, y: p1.y - p2.y)
    }
}
class Person {
    var age = 0
    var point: Point = Point()
}
var p: Person? = Person()
p?.point +- Point(x: 10, y: 20)

到此这篇关于Swift运算符使用方法浅析的文章就介绍到这了,更多相关Swift运算符内容请搜索好代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持好代码网!

标签: Swift 运算符