iOS Swift, Enum CaseIterable extension

后端 未结 1 349
终归单人心
终归单人心 2021-01-18 04:28

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

1条回答
  •  借酒劲吻你
    2021-01-18 04:43

    Not all enumeration types have an associated RawValue, and if they have then it is not necessarily a String.

    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 }
        }
    }
    

    Examples:

    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'
    

    0 讨论(0)
提交回复
热议问题