iOS Swift,Enum CaseIterable扩展 [英] iOS Swift, Enum CaseIterable extension
问题描述
我正在尝试为CaseIterable
的枚举编写扩展名,以便我可以获取原始值的数组而不是大小写,但是我不确定如何做到这一点
Im trying to write an extension for an enum that is CaseIterable
so that i can get an array of the raw values instead of the cases, Im not entirely sure how to do that though
extension CaseIterable {
static var allValues: [String] {
get {
return allCases.map({ option -> String in
return option.rawValue
})
}
}
}
我需要以某种方式添加where子句,如果我没有where子句,我会收到一条错误消息,提示'map' produces '[T]', not the expected contextual result type '[String]'
i need to add a where clause somehow, if i dont have a where clause i get an error saying 'map' produces '[T]', not the expected contextual result type '[String]'
有人知道这样做有什么好方法吗?
Anyone know if there is a good way of going about this?
我的枚举我想让这个功能看起来像这样
my enums i want this function to work on look a bit like this
enum TypeOptions: String, CaseIterable {
case All = "all"
case Article = "article"
case Show = "show"
}
推荐答案
并非所有枚举类型都具有关联的RawValue
,如果具有,则不一定是String
.
Not all enumeration types have an associated RawValue
, and if they have then it is not necessarily a String
.
因此,您需要将扩展名限制为RawRepresentable
的枚举类型,并将返回值定义为RawValue
的数组:
Therefore you need to restrict the extension to enumeration types which are RawRepresentable
, and define the return value as an array of RawValue
:
extension CaseIterable where Self: RawRepresentable {
static var allValues: [RawValue] {
return allCases.map { $0.rawValue }
}
}
示例:
enum TypeOptions: String, CaseIterable {
case all
case article
case show
case unknown = "?"
}
print(TypeOptions.allValues) // ["all", "article", "show", "?" ]
enum IntOptions: Int, CaseIterable {
case a = 1
case b = 4
}
print(IntOptions.allValues) // [1, 4]
enum Foo: CaseIterable {
case a
case b
}
// This does not compile:
print(Foo.allValues) // error: Type 'Foo' does not conform to protocol 'RawRepresentable'
这篇关于iOS Swift,Enum CaseIterable扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!