找到两个对象之间的已更改属性

时间:2017-12-28 18:29:14

标签: ios swift diff

我正在研究实体差异算法。我试图找到两个对象之间和之后的更改属性。是否可以比较两个对象的值?它们都是Any类型,无法进行比较。

import Foundation

class Person {
    var gender: Gender = .female
    let dateOfBirth: Date

    init(dateOfBirth: Date) {
        self.dateOfBirth = dateOfBirth
    }

    class func GetDateFromString(DateStr: String)-> Date
    {
        let calendar = NSCalendar(identifier: NSCalendar.Identifier.gregorian)
        let DateArray = DateStr.components(separatedBy: "/")
        let components = NSDateComponents()
        components.year = Int(DateArray[2])!
        components.month = Int(DateArray[1])!
        components.day = Int(DateArray[0])!
        components.timeZone = TimeZone(abbreviation: "GMT+0:00")
        let date = calendar?.date(from: components as DateComponents)

        return date!
    }

    enum Gender {
        case male
        case female
        case unknown
    }


    func update(oldValue: Person?,entity: Person) {
        if let oldValue = oldValue {
            let mirror1 = Mirror(reflecting: oldValue)
            let mirror2 = Mirror(reflecting: entity)


            for (child1,child2) in zip(mirror1.children,mirror2.children){
                if let dob1 = child1 as? Gender, let dob2 = child2 as? Gender {
                    if dob1 == dob2 {
                        print("not equal")
                    }
                }
            }

        }
    }

}

extension Person: Equatable {
    static func == (lhs: Person, rhs: Person) -> Bool {
        return lhs.gender == rhs.gender && lhs.dateOfBirth == rhs.dateOfBirth
    }
}




let user1 = Person(dateOfBirth: Person.GetDateFromString(DateStr: "12/1/1987"))
let user2 = Person(dateOfBirth: Person.GetDateFromString(DateStr: "10/10/1987"))
user1.gender = .male

1 个答案:

答案 0 :(得分:0)

如果你关心的只是平等,你可以遵守Equatable协议。如果您需要大于/小于比较,则可以符合Comparable。以下是如何使用equatable:

的示例
extension Person: Equatable {
    static func == (lhs: Person, rhs: Person) -> Bool {
        return lhs.gender == rhs.gender && lhs.dateOfBirth == rhs.dateOfBirth
    }
}