How to make a Swift String enum available in Objective-C?

前端 未结 10 2206
情深已故
情深已故 2020-12-01 07:09

I have this enum with String values, which will be used to tell an API method that logs to a server what kind of serverity a message has. I\'m using Swift 1.2,

10条回答
  •  余生分开走
    2020-12-01 07:37

    This is my use case:

    • I avoid hard-coded Strings whenever I can, so that I get compile warnings when I change something
    • I have a fixed list of String values coming from a back end, which can also be nil

    Here's my solution that involves no hard-coded Strings at all, supports missing values, and can be used elegantly in both Swift and Obj-C:

    @objc enum InventoryItemType: Int {
        private enum StringInventoryItemType: String {
            case vial
            case syringe
            case crystalloid
            case bloodProduct
            case supplies
        }
    
        case vial
        case syringe
        case crystalloid
        case bloodProduct
        case supplies
        case unknown
    
        static func fromString(_ string: String?) -> InventoryItemType {
            guard let string = string else {
                return .unknown
            }
            guard let stringType = StringInventoryItemType(rawValue: string) else {
                return .unknown
            }
            switch stringType {
            case .vial:
                return .vial
            case .syringe:
                return .syringe
            case .crystalloid:
                return .crystalloid
            case .bloodProduct:
                return .bloodProduct
            case .supplies:
                return .supplies
            }
        }
    
        var stringValue: String? {
            switch self {
            case .vial:
                return StringInventoryItemType.vial.rawValue
            case .syringe:
                return StringInventoryItemType.syringe.rawValue
            case .crystalloid:
                return StringInventoryItemType.crystalloid.rawValue
            case .bloodProduct:
                return StringInventoryItemType.bloodProduct.rawValue
            case .supplies:
                return StringInventoryItemType.supplies.rawValue
            case .unknown:
                return nil
            }
        }
    }
    

提交回复
热议问题