Swift 特性 1 - 重载运算符

SwiftiBcker • 于 2015-09-08 10:13:51 +0800 • 最后由 clyyuanzi2015-09-08 14:43:13 +0800 1789 阅读

Swift加了个OC里没有的特性-运算符重载,啥意思呢?

并不是Swift独有

其实运算符重载并不是什么新概念,很多语言都,例如C++,ruby等,不过OC是没有的,所以对于以前只做过OC开发的同学来说值得看一下

用途

数字运算符+ let a = 1 let b = 2 let c = a + b print("a+b=\(c)") c=a+b,很容易理解,其中的+为自带运算符

但是如果是一个结构体相加呢? 例如官方给出的例子: ``` struct Vector2D { var x = 0.0 var y = 0.0 }

let v1 = Vector2D(x: 2.0, y: 3.0) let v2 = Vector2D(x: 1.0, y: 4.0) let v3 = v1 + v2 ``` 嗯,编译器并不知道要如何计算,所以如果想实现这里的+号,就可以用到重载运算符了。

内容改为:

``` struct Vector2D { var x = 0.0 var y = 0.0 }

func + (left: Vector2D, right: Vector2D) -> Vector2D { return Vector2D(x: left.x + right.x, y: left.y + right.y) }

let v1 = Vector2D(x: 2.0, y: 3.0) let v2 = Vector2D(x: 1.0, y: 4.0) let v3 = v1 + v2 ```

这样就重载了+运算符实现了结构体Vector2D的+操作

@assignment

对于前置和后置++这类运算符

b = ++a

不仅会a修改自身的值,还会赋值给b,要实现此种自赋值的操作,就得需要加上@assignment修饰符

``` @prefix @assignment 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) ```

类似的原来还可以实现减号等,大家玩得开心~

运算符目录

``` << Bitwise left shift

Bitwise right shift Multiplicative (Left associative, precedence level 150) * Multiply / Divide % Remainder &* Multiply, ignoring overflow &/ Divide, ignoring overflow &% Remainder, ignoring overflow & Bitwise AND Additive (Left associative, precedence level 140) + Add - Subtract &+ Add with overflow &- Subtract with overflow | Bitwise OR ^ Bitwise XOR Range (No associativity, precedence level 135) .. Half-closed range ... Closed range Cast (No associativity, precedence level 132) is Type check as Type cast Comparative (No associativity, precedence level 130) < Less than <= Less than or equal Greater than = Greater than or equal == Equal != Not equal === Identical !== Not identical ~= Pattern match Conjunctive (Left associative, precedence level 120) && Logical AND Disjunctive (Left associative, precedence level 110) || Logical OR Ternary Conditional (Right associative, precedence level 100) ?: Ternary conditional Assignment (Right associative, precedence level 90) = Assign *= Multiply and assign /= Divide and assign %= Remainder and assign += Add and assign -= Subtract and assign <<= Left bit shift and assign = Right bit shift and assign &= Bitwise AND and assign ^= Bitwise XOR and assign |= Bitwise OR and assign &&= Logical AND and assign ||= Logical OR and assign ```

本帖已被设为精华帖!
回复: 1
  • 请注意单词拼写,以及中英文排版,参考此页
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`, 更多语法请见这里 Markdown 语法
  • 支持表情,见 Emoji cheat sheet
  • @name 会链接到用户页面,并会通知他
  • 上传图片, 支持拖拽和剪切板黏贴上传, 格式限制 - jpg, png, gif
Ctrl+Enter