ios - iOS Swift,枚举 CaseIterable 扩展
问题描述
我试图为枚举编写一个扩展,CaseIterable
以便我可以获得原始值的数组而不是案例,但我不完全确定如何做到这一点
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]'
任何人都知道是否有解决此问题的好方法?
我的枚举我希望这个函数看起来有点像这样
enum TypeOptions: String, CaseIterable {
case All = "all"
case Article = "article"
case Show = "show"
}
解决方案
并非所有枚举类型都有关联RawValue
的 ,如果有,则不一定是String
。
因此,您需要将扩展限制为枚举类型RawRepresentable
,并将返回值定义为以下数组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'
推荐阅读
- c# - 如何实现 Ellipse WPF 扩展?
- php - How to get an access to webpage from external php file
- apache-kafka - kafka use-case for error topics
- sql - Oracle 11g:表校验和或哈希
- mongodb - Error when trying to use MongoDB's cursor sort in Perl
- oozie - OOzie HA 作业在一个或两个上运行
- opengl-es - 基于顶点的openGL中不同颜色三角形的平面着色
- r - r containerRit Dockerfile 脚本文件未找到
- java - Java Pattern Matcher Incorrectly matches sub string
- excel - code not returning the value when it finds the text vba