有没有办法在Swift中为`struct`自动定义比较(`==`)函数?

Val*_*gin 3 swift swift-structs

让我们假设我们struct在 Swift 中有一个相当大的:

struct SuperStruct {
    var field1: Int = 0
    var field2: String = ""
    // lots of lines...
    var field512: Float = 0.0
}
Run Code Online (Sandbox Code Playgroud)

.. 然后我们需要实现Equatable协议:

extension SuperStruct: Equatable {
}

func ==(lhs: SuperStruct, rhs: SuperStruct) -> Bool {
    return
        lhs.field1 == rhs.field1 &&
        lhs.field2 == rhs.field2 &&
        // lots of lines...
        lhs.field512 == rhs.field512
}
Run Code Online (Sandbox Code Playgroud)

...我们需要编写大量愚蠢的代码行。有没有办法“要求”编译器为我们“做”它?

dfr*_*fri 5

以下答案显示了一种可能的解决方案;可能不是推荐的(但可能对这个问题的未来读者感兴趣)。


如果您有大量的属性,它们都属于数量有限的不同类型,您可以使用一个Mirror结构实例并遍历结构的属性;对于每次尝试转换为您知道属性的不同类型。

在观看了以下 WWDC 2015 会议后(感谢 Leo Dabus!),我已经编辑了之前的答案(我认为更简洁的内容):

我也会在这个答案的底部留下最初的答案,因为它展示了一种替代的、较少面向协议的方法来利用这个Mirror解决方案。

Mirror & 面向协议的解决方案:

/* Let a heterogeneous protocol act as "pseudo-generic" type
   for the different (property) types in 'SuperStruct'         */
protocol MyGenericType {
    func isEqualTo(other: MyGenericType) -> Bool
}
extension MyGenericType where Self : Equatable {
    func isEqualTo(other: MyGenericType) -> Bool {
        if let o = other as? Self { return self == o }
        return false
    }
}

/* Extend types that appear in 'SuperStruct' to MyGenericType  */
extension Int : MyGenericType {}
extension String : MyGenericType {}
extension Float : MyGenericType {}
    // ...

/* Finally, 'SuperStruct' conformance to Equatable */
func ==(lhs: SuperStruct, rhs: SuperStruct) -> Bool {

    let mLhs = Mirror(reflecting: lhs).children.filter { $0.label != nil }
    let mRhs = Mirror(reflecting: rhs).children.filter { $0.label != nil }

    for i in 0..<mLhs.count {
        guard let valLhs = mLhs[i].value as? MyGenericType, valRhs = mRhs[i].value as? MyGenericType else {
            print("Invalid: Properties 'lhs.\(mLhs[i].label!)' and/or 'rhs.\(mRhs[i].label!)' are not of 'MyGenericType' types.")
            return false
        }
        if !valLhs.isEqualTo(valRhs) {
            return false
        }
    }
    return true
}
Run Code Online (Sandbox Code Playgroud)

用法示例:

/* Example */
var a = SuperStruct()
var b = SuperStruct()
a == b // true
a.field1 = 2
a == b // false
b.field1 = 2
b.field2 = "Foo"
a.field2 = "Foo"
a == b // true
Run Code Online (Sandbox Code Playgroud)

以前的Mirror解决方案:

/* 'SuperStruct' conformance to Equatable */
func ==(lhs: SuperStruct, rhs: SuperStruct) -> Bool {

    let mLhs = Mirror(reflecting: lhs).children.filter { $0.label != nil }
    let mRhs = Mirror(reflecting: rhs).children.filter { $0.label != nil }

    for i in 0..<mLhs.count {
        switch mLhs[i].value {
        case let valLhs as Int:
            guard let valRhs = mRhs[i].value as? Int where valRhs == valLhs else {
                return false
            }
        case let valLhs as String:
            guard let valRhs = mRhs[i].value as? String where valRhs == valLhs else {
                return false
            }
        case let valLhs as Float:
            guard let valRhs = mRhs[i].value as? Float where valRhs == valLhs else {
                return false
            }
            /* ... extend with one case for each type
            that appear in 'SuperStruct'  */
        case _ : return false
        }
    }
    return true
}
Run Code Online (Sandbox Code Playgroud)

用法示例:

/* Example */
var a = SuperStruct()
var b = SuperStruct()
a == b // true
a.field1 = 2
a == b // false
b.field1 = 2
b.field2 = "Foo"
a.field2 = "Foo"
a == b // true
Run Code Online (Sandbox Code Playgroud)


pka*_*amb 4

在 Swift 4.1 中,如果所有类型的成员都是 Equatable/Hashable,则 Equatable/Hashable 类型现在会合成与 Equatable/Hashable 的一致性

SE-0185

综合 Equatable 和 Hashable 一致性

开发人员必须编写大量样板代码来支持复杂类型的可等性和可哈希性。该提案为编译器提供了一种自动综合 Equatable 和 Hashable 一致性的方法,以在已知可能生成正确实现的场景子集中减少此样板文件。

https://github.com/apple/swift-evolution/blob/master/proposals/0185-synthesize-equatable-hashable.md