微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Swift - 运算符重载和运算符函数

1,通过重载加号运算符,使自定义的两个坐标结构体对象实现相加:

struct CenterPointer{
    var x=0,y=0
}
 
func + (left:CenterPointer,right:CenterPointer) -> CenterPointer{
    return CenterPointer(x:left.x+right.y,y:left.y+right.y)
}
 
let pointer1 = CenterPointer(x:2,y:3)
let pointer2 = CenterPointer(x:4,y:5)
let pointer3 = pointer1 + pointer2

2,重载判断运算符 ,实现判断自定义类型是否相等

func == (left:CenterPointer,right:CenterPointer) -> Bool {
    return (left.x == right.x) && (left.y == right.y)
}
 
func != (left:CenterPointer,right:CenterPointer) -> Bool {
    return !(left == right)
}

3,组合运算符 ,即将其他运算符和赋值运算符组合在一起,注意要把运算符左参数设置成inout类型

func += (inout left:CenterPointer,right:CenterPointer){
    left = left + right
}
 
var pointer1 = CenterPointer(x:2,y:3)
var pointer2 = CenterPointer(x:4,y:5)
pointer1 += pointer2

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐