gpt4 book ai didi

swift - 如何在枚举列表中查找枚举?

转载 作者:行者123 更新时间:2023-11-28 10:56:51 25 4
gpt4 key购买 nike

我想确定枚举列表中是否存在枚举。直觉上我会这样做:

if myEnum == (.one || .two) { return true }
else { return false }

当然不行。

我知道我能做到:

if myEnum == .one || myEnum == .two { return true }
else { return false }

或者

if [EnumType.one, EnumType.two].contains(myEnum) { return true }
else { return false }

但我今天只想玩得开心:)

我正在考虑使用过滤器,但它似乎太过分了。

你有什么想法吗?

非常感谢。

蒂埃里

最佳答案

你可以做到

//: Playground - noun: a place where people can play

import Cocoa

enum MyEnum {
case one
case two
case three
case four
}

let list: [MyEnum] = [.one, .two, .three, .four]

if list.contains(.one) {
// Contains
} else {
// Doesn't Contain
}

如果您有关联数据,则必须使您的枚举 Equatable 才能正常工作。例如:

//: Playground - noun: a place where people can play

import Cocoa

enum MyEnum: Equatable {
case one
case two
case three
case four
case other(String)

static func ==(lhs: MyEnum, rhs: MyEnum) -> Bool {
switch (lhs, rhs) {
case (.one, .one),
(.two, .two),
(.three, .three),
(.four, .four):
return true

case (.other(let lhsString), .other(let rhsString)) where lhsString == rhsString:
return true

default:
return false
}
}
}

let list: [MyEnum] = [.one, .two, .three, .four, .other("test")]

if list.contains(.one) {

} else {

}

关于swift - 如何在枚举列表中查找枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43003831/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com