简体   繁体   English

如何比较同一Swift枚举的不同实例?

[英]How does one compare different instances of the same Swift enum?

Take this enum and the three literal instances of it that follow: 列举该枚举及其后的三个文字实例:

enum Types {
    case string(String), int(Int), bool(Bool)
}

let t1 = Types.string("one")
let t2 = Types.string("two")
let t3 = Types.int(3)

How can these be compared so that t1 and t2 match (as the same enum case, even though their values differ), whilst t1 and t3 do not match (as they are different cases of the same enum), like this?: 如何比较它们,以使t1t2匹配(即使它们的值不同,也等于相同的枚举情况),而t1t3不匹配(因为它们是同一枚举的不同情况),就像这样?

func compare (lhs: Types, rhs: Types) -> Bool {
    return lhs == rhs
}

print(compare(lhs: t1, rhs: t2)) // prints "true"
print(compare(lhs: t1, rhs: t3)) // prints "false"

You can achieve that by conforming Types to Equatable protocol: 您可以通过使Types符合Equatable协议来实现:

extension Types: Equatable {
    static func == (lhs: Types, rhs: Types) -> Bool {
        switch (lhs, rhs) {
        case (.string, .string), (.int, .int), (.bool, .bool):
            return true
        default:
            return false
        }
    }
}

print(t1 == t2) // true
print(t1 == t3) // false

UPD. UPD。

You should think about formatting your code. 您应该考虑格式化代码。 Swift api design guidelines said: Swift API设计指南说:

Follow case conventions. 请遵循大小写约定。 Names of types and protocols are UpperCamelCase. 类型和协议的名称为UpperCamelCase。 Everything else is lowerCamelCase. 其他一切都是lowerCamelCase。

So, there is no uppercase case s should appear in your code. 所以,没有大写的case S的关系出现在你的代码。

Spaces between parentheses should be trimmed as well. 括号之间的间隔也应修剪。


UPD 1. UPD 1。

if I want to get the value "one" out of let t1 = Types.String( "one" ), is that possible and if so how? 如果我想让t1 = Types.String(“ one”)获得值“ one”,那有可能吗?

Sure. 当然。 The if case let ... can help you here: if case let ...可以在这里为您提供帮助:

if case let .string(value) = t1 {
    print(value) // "one"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM