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)在自定义运算符中还可以设定自定义运算符的优先级和结合性,来处理更复杂的任务。 总结
以上是内存溢出为你收集整理的swift2 运算符函数全部内容,希望文章能够帮你解决swift2 运算符函数所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)