Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add raw values for an enum that doesn't have it?

Tags:

enums

swift

Given an external enum that I can't change:

enum MyEnum {
  case first
  case second
}

How would I best make this RawRepresentable, or at least convertible to an Int (or String) ?

I could write an extension to mimic rawValue, but this feels rather clumsy:

extension MyEnum {

    enum EnumError: Error {
        case invalidValue
    }

    init (rawValue: Int) throws {
        switch rawValue {
        case 0:
            self = .first
        case 1:
            self = .second
        default:
            throw EnumError.invalidValue
        }
    }

    var rawValue: Int {
        switch self {
        case .first:
            return 0
        case .second:
            return 1
        }
    }
}

What is a better way?

like image 797
Niklas Avatar asked Dec 21 '25 17:12

Niklas


1 Answers

This works:

enum MyEnum {
    case first
    case second
}

extension MyEnum {
    enum MyExtendedEnum:Int {
        case first
        case second
    }
}

Its a bit more cleaner code anyways, and your call is now:

let myVar = MyEnum.MyExtendedEnum.RawValue()

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!