【问题标题】:Swift: checking 2 object from same class have different values?Swift:检查来自同一类的 2 个对象是否具有不同的值?
【发布时间】:2020-08-24 19:45:55
【问题描述】:

我在我的项目中使用 swift。我有 2 个来自同一类的对象(例如来自 MyClass 类的对象 A 和对象 B):

class MyClass: NSObject {
    var someString: String = ""
    var someInt: Int = 0
}
...
let A = MyClass()
A.someString = "A object"
A.someInt = 1

let B = MyClass()
B.someString = "B object"
B.someInt = 2

我如何检查相同的属性是否具有相同的值,如果不是,则返回属性的值和键?

我认为我们可以通过在彼此内部使用带有 2 个 for 循环的 Mirror 来做到这一点,我在写吗?

【问题讨论】:

  • 您需要为任何班级或仅针对特定班级这样做吗?
  • 特定类
  • 所以您可以简单地在函数中执行if a.someString != b.someString { return ("someString", a.someString) } 之类的操作?
  • 我使用了一些简单的类(只有 2 个属性),想象一个有 20 个属性的类。那我该怎么办?
  • 是的,但是你需要为每个属性编写特定的代码,我觉得你不想这样做。

标签: swift


【解决方案1】:

我认为您正在寻找类似的东西:

import Foundation

class MyClass {
    var someString: String = ""
    var someInt: Int = 0
}

let a = MyClass()
a.someString = "A object"
a.someInt = 1

let b = MyClass()
b.someString = "B object"
b.someInt = 2

func compare<T: MyClass>(_ instance: T, with instance2: T) -> [String: AnyHashable] {
    let sourceMirror = Mirror(reflecting: instance)
    let targetMirror = Mirror(reflecting: instance2)
    
    var output = [String: AnyHashable]()
    
    for sourceChild in sourceMirror.children {
        guard let label = sourceChild.label else { continue }
        
        guard let targetChild = (targetMirror.children.first { $0.label! == label }) else {
            fatalError("Failed to find target child, since types are same this fatal error should not be fired")
        }
        
        guard
            let firstValue = sourceChild.value as? AnyHashable,
            let secondValue = targetChild.value as? AnyHashable
        else {
            continue
        }
        
        guard firstValue != secondValue else { continue }
        
        output[label] = secondValue
    }
    
    return output
}

for result in compare(a, with: b) {
    print("label: \(result.key), value: \(result.value)")
}

这种方法的缺点是你的所有字段都必须符合 Hashable 协议才能看到它们之间的区别。

输出是:

label: someInt, value: 2
label: someString, value: B object

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多