前端之家收集整理的这篇文章主要介绍了
swift 重载运算符,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
//(1) 自定义一个*运算符,左边是String类型, 右侧为Int类型
func * (left: String,right: Int) -> String {
var result = ""
for i in 0..<right {
result += "\(i)" + left
}
return result
}
let a = "Hello " * 3
println(a) //0Hello 1Hello 2Hello
//(2) 覆盖已知的运算符
func * (left: Int,right: Int) -> Int {
return 0
}
let b = 10 * 10
println(b) //0
//(3) 自定义一个单项事运算符 ++
postfix func ++ (left: Double) -> String {
return "\(left)" + "++"
}
println(0.0++) //0.0++
//(4) 复合运算符重载
func += (inout left: String,right: Int) {
left = left + "\(right)"
}
var str = "aaaa"
str += 10
println(str) //aaaa10
//(5) 完全自定义符号 “<^|^>” [postfix]后置 [prefix]前置 [infix]二项演算
infix operator <^|^> {}
func <^|^> (left: Any,right:Any) -> String {
return "