美文网首页Swift
Swift之EquaTable

Swift之EquaTable

作者: 小羊爱学习 | 来源:发表于2023-11-14 11:00 被阅读0次

    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
        }
    }
    

    相关文章

      网友评论

        本文标题:Swift之EquaTable

        本文链接:https://www.haomeiwen.com/subject/jvljwdtx.html