iOS Swift,Enum CaseIterable扩展 [英] iOS Swift, Enum CaseIterable extension

查看:380
本文介绍了iOS Swift,Enum CaseIterable扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆