是否可以为该自定义类中的自定义类重载等价(==)运算符。但是我知道可以让这个运算符重载在类范围之外。感谢任何示例代码。 提前谢谢。
答案 0 :(得分:28)
添加全局功能。例如:
class CustomClass {
var id = "my id"
}
func ==(lhs: CustomClass, rhs: CustomClass) -> Bool {
return lhs == rhs
}
func !=(lhs: CustomClass, rhs: CustomClass) -> Bool {
return !(lhs == rhs)
}
class CustomClass: Equatable {
var id = "my id"
}
func ==(left: CustomClass, right: CustomClass) -> Bool {
return left.id == right.id
}
class CustomClass {
var id = "my id"
}
extension CustomClass: Equatable {
static func ==(lhs: CustomClass, rhs: CustomClass) -> Bool {
return lhs.id == rhs.id
}
}
答案 1 :(得分:6)
不,运算符使用全局函数重载。