简体   繁体   中英

How could I use the multiple Enum raw values of type Int in Swift?

How could I use multiple Enum raw values of type Int in Swift? I am getting this error:

Expected identifier after comma in enum 'case' declaration.

In my case I want onGoing case to accept multiple Int raw values so that code can returns the status accordingly.

enum STATUS_CODE : Int {
    
    case onGoing    = 5, 50,70, 90
    case atWorkshop = 10
    case completed  = 16
    case comedy     = 35
    case crime      = 80
    case NoDate     = 0
    
    func getString() -> String {
        switch self {
        case .onGoing   : return "New order"
        case .atWorkshop: return "At workshop"
        case .completed : return "Animation"
        case .comedy    : return "Comedy"
        case .crime     : return "Crime"
        case .NoDate    : return "No Order"
        }
    }
}

Enum cases can not have multiple rawValues. Becase imagine you call this:

print( STATUS_CODE.onGoing.rawValue )

What value you expect to be printed?


Instead you can have a custom enum like the one you think of:

enum STATUS_CODE: RawRepresentable {

    init(rawValue: Int) {
        switch rawValue {
        case 5, 50,70, 90: self = .onGoing(rawValue)
        case 10: self = .atWorkshop
        case 16: self = .completed
        case 35: self = .comedy
        case 80: self = .crime
        case 0: self = .NoDate

        default: self = .unknown(rawValue)
        }
    }

    var rawValue: Int {
        switch self {
        case .onGoing(let rawValue): return rawValue
        case .atWorkshop: return 10
        case .completed: return 16
        case .comedy: return 35
        case .crime: return 80
        case .NoDate: return 0
        case .unknown(let rawValue): return rawValue
        }
    }

    case onGoing(Int)
    case atWorkshop
    case completed
    case comedy
    case crime
    case NoDate

    case unknown(Int)

    func getString() -> String {
        switch self {
        case .onGoing   : return "New order"
        case .atWorkshop: return "At workshop"
        case .completed : return "Animation"
        case .comedy    : return "Comedy"
        case .crime     : return "Crime"
        case .NoDate    : return "No Order"

        case .unknown(let rawValue): return "Unknown \(rawValue)"
        }
    }
}

ofcourse it is a demo and can be refactored ;)

You cannot. As the documentation declares, "Each raw value must be unique within its enumeration declaration." https://docs.swift.org/swift-book/LanguageGuide/Enumerations.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM