Test enum for equality in for … where clause

不想你离开。 提交于 2020-01-03 16:37:14

问题


How can I test for enum equality when a case has an associated value? A contrived example:

enum Status : Equatable {
    case success
    case failed(error: String)

    static func == (lhs: Status, rhs: Status) -> Bool {
        switch (lhs, rhs) {
        case (.success, .success), (.failed, .failed):
            return true
        default:
            return false
        }
    }
}

let statuses = [
    Status.success,
    .failed(error: "error 1"),
    .failed(error: "error 2"),
    .success
]

// Failed: Binary operator '==' cannot be applied to operands of type 'Status' and '_'
for s in statuses where s == .failed {
    print(s)
}

(I know I can test for s != .success but the actual enum has more cases so they are a hassle)


回答1:


You can use if case:

for status in statuses {
    if case .failed = status {
        ...
    }
}

But, unfortunately, you can't use case with the where clause of for loop.


In this case, though, because you've defined .failed to be equal to another regardless of what the error associated value was, you theoretically could do:

for status in statuses where status == .failed(error: "") {
    show("\(status)")
}

I'm not crazy about that pattern because (a) it's contingent upon the fact that .failed values are equal even if they have different error associated values; and (b) it results in code that is easily misunderstood.



来源:https://stackoverflow.com/questions/44099325/test-enum-for-equality-in-for-where-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!