swift2 运算符函数

前端之家收集整理的这篇文章主要介绍了swift2 运算符函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

运算符函数


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 是一个新的Vector2D,值为 (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 为 (-3.0,-4.0)
let alsoPositive = -negative
// alsoPositive 为 (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 现在为 (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 现在是 (4.0,5.0)
// afterIncrement 现在也是 (4.0,5.0)


比较运算符


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("这两个向量是相等的.")
}


自定义运算符

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 现在是 (2.0,8.0)
// afterDoubling 现在也是 (2.0,8.0)
自定义运算符中还可以设定自定义运算符的优先级和结合性,来处理更复杂的任务。
原文链接:https://www.f2er.com/swift/326458.html

猜你在找的Swift相关文章