How to get enum from raw value in Swift?

前端 未结 7 1005
一向
一向 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:21

    With Swift 4.2 and CaseIterable protocol it is not that hard at all!

    Here is an example of how to implement it.

    import UIKit
    
    private enum DataType: String, CaseIterable {
        case someDataOne = "an_awesome_string_one"
        case someDataTwo = "an_awesome_string_two"
        case someDataThree = "an_awesome_string_three"
        case someDataFour = "an_awesome_string_four"
    
        func localizedString() -> String {
            // Internal operation
            // I have a String extension which returns its localized version
            return self.rawValue.localized
        }
    
        static func fromLocalizedString(localizedString: String) -> DataType? {
            for type in DataType.allCases {
                if type.localizedString() == localizedString {
                    return type
                }
            }
            return nil
        }
    
    }
    
    // USAGE EXAMPLE
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if let dataType = DataType.fromLocalizedString(localizedString: self.title) {
            loadUserData(type: dataType)
        }
    }
    

    You can easily modify it to return the DataType based on the rawValue. I hope it helps!

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