# Swift 运算符重载简介

## 挑战

`"abc" * 5 = "abc" + "abc" + "abc" + "abc" + "abc" = "abcabcabcabcabc"`

• 定义变量 `result` 并进行初始化 —— 默认字符串。
• 从 2 开始循环，一直到待拼接的字符串数目终止，每次迭代只做一件事 —— 把字符串拼接到 `result` 末尾。
• 打印 `result`

## 基本运算符重载

`func *(lhs: String, rhs: Int) -> String { }`

`var result = lhs`

`for _ in 2...rhs { }`

`result += lhs`

`result = result + lhs`

`return result`

`let u = "abc"let v = u * 5`

## 泛型运算符

`protocol Type { }`

`func +=(inout lhs: Self, rhs: Self)`

`func +(lhs: Self, rhs: Self) -> Self`

`extension String: Type {}extension Int: Type {}extension Double: Type {}extension Float: Type {}`

`func *<T: Type>(lhs: T, rhs: Int) -> T { }`

`func *<T where T: Type>(lhs: T, rhs: Int) -> T`

`var result = lhs for _ in 2...rhs {     result += lhs    } return result`

`let x = "abc"let y = x * 5 let a = 2let b = a * 5 let c = 3.14let d = c * 5 let e: Float = 4.56let f = e * 5`

## 自定义运算符

`infix operator ** {associativity left precedence 150}`

• 自定义乘法运算符的名称是 **。
• 类型是 `中缀运算符(infix)` 因为它有两个操作数。
• 运算顺序从左至右，因此是左结合。
• 优先级设置为 150 —— 与标准乘法运算符相同，因为它是高优先级运算符。

`func **<T: Type>(lhs: T, rhs: Int) -> T { }`

`var result = lhs for _ in 2...rhs {     result += lhs    } return result`

`let g = "abc"let h = g ** 5 let i = 2let j = i ** 5 let k = 3.14let l = k ** 5 let m: Float = 4.56let n = m ** 5`

## 复合运算符

`infix operator **= {associativity left precedence 150}`

`func **=<T: Type>(inout lhs: T, rhs: Int) { }`

`lhs = lhs ** rhs`

`var o = "abc"o **= 5 var q = 2q **= 5 var s = 3.14s **= 5 var w: Float = 4.56w **= 5`