//(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 "
swift 重载运算符
最新推荐文章于 2020-06-06 14:21:19 发布