簡體   English   中英

如何比較同一Swift枚舉的不同實例?

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

列舉該枚舉及其后的三個文字實例:

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

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

如何比較它們,以使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"

您可以通過使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。

您應該考慮格式化代碼。 Swift API設計指南說:

請遵循大小寫約定。 類型和協議的名稱為UpperCamelCase。 其他一切都是lowerCamelCase。

所以,沒有大寫的case S的關系出現在你的代碼。

括號之間的間隔也應修剪。


UPD 1。

如果我想讓t1 = Types.String(“ one”)獲得值“ one”,那有可能嗎?

當然。 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