How to get enum from raw value in Swift?

前端 未结 7 1087
一向
一向 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:16

    I think this is a quick and clean solution for swift 4.2 (you can c&p to playground)

    import UIKit
    
    public enum SomeEnum: String, CaseIterable {
        case sun,moon,venus,pluto
    }
    
    let str = "venus"
    let newEnum = SomeEnum.allCases.filter{$0.rawValue == str}.first
    // newEnum is optional
    if let result = newEnum {
        print(result.rawValue)
    }
    

提交回复
热议问题