How to get enum from raw value in Swift?

前端 未结 7 1111
一向
一向 2020-12-13 23:25

I\'m trying to get enum type from raw value:

enum TestEnum: String {
    case Name
    case Gender
    case Birth

    var rawValue: String {
        switch          


        
7条回答
  •  死守一世寂寞
    2020-12-14 00:06

    You can define enum like this -

    enum TestEnum: String {
        case Name, Gender, Birth
    }
    

    OR

    enum TestEnum: String {
        case Name
        case Gender
        case Birth
    }
    

    you can provide an init method which defaults to one of the member values.

    enum TestEnum: String {
        case Name, Gender, Birth
    
        init() {
            self = .Gender
        }
    }
    

    In the example above, TestEnum.Name has an implicit raw value of "Name", and so on.

    You access the raw value of an enumeration case with its rawValue property:

    let testEnum = TestEnum.Name.rawValue
    // testEnum is "Name"
    let testEnum1 = TestEnum() 
    // testEnum1 is "Gender"
    

提交回复
热议问题