Overloading equivalence (==) operator for custom class in Swift

懵懂的女人 提交于 2019-12-01 02:32:35

Add global functions. For example:

class CustomClass {
    var id = "my id"
}

func ==(lhs: CustomClass, rhs: CustomClass) -> Bool {
    return lhs == rhs
}
func !=(lhs: CustomClass, rhs: CustomClass) -> Bool {
    return !(lhs == rhs)
}

To conform Equatable protocol in Swift 2

class CustomClass: Equatable {
    var id = "my id"
}

func ==(left: CustomClass, right: CustomClass) -> Bool {
    return left.id == right.id
}

To conform Equatable protocol in Swift 3

class CustomClass {
    var id = "my id"
}

extension CustomClass: Equatable {
    static func ==(lhs: CustomClass, rhs: CustomClass) -> Bool {
        return lhs.id == rhs.id
    }
}

No, operators are overloaded using global functions.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!