Equatable
可以进行值相等比较的类型。
protocol Equatable
比较两个类是否相等
class StreetAddress {
let number: String
let street: String
let unit: String?
init(_ number: String, _ street: String, unit: String? = nil) {
self.number = number
self.street = street
self.unit = unit
}
}
extension StreetAddress: Equatable {
static func == (lhs: StreetAddress, rhs: StreetAddress) -> Bool {
return
lhs.number == rhs.number &&
lhs.street == rhs.street &&
lhs.unit == rhs.unit
}
}
对于结构,其所有存储的属性都必须符合Equatable。
对于枚举,其所有关联值都必须符合Equatable。
基本数据类型是都符合Equatable的,因此多个类时需要都实现Equatable。
class StreeAddress{
let number : String
let street : String
let unit : String?
let demo : Demo
init(_ number : String , _ street : String , _ name : String, _ unit : String? = nil) {
self.number = number
self.street = street
self.unit = unit
self.demo = Demo(name)
}
}
class Demo{
let name : String
init(_ name : String = "名字") {
self.name = name
}
}
extension StreeAddress : Equatable{
static func == (lhs: StreeAddress, rhs: StreeAddress) -> Bool {
return
lhs.number == rhs.number &&
lhs.street == rhs.street &&
lhs.unit == rhs.unit &&
lhs.demo == rhs.demo
}
}
extension Demo : Equatable{
static func == (lhs: Demo, rhs: Demo) -> Bool {
return lhs.name == rhs.name
}
}
网友评论