Search code examples
iosswift

Enum with raw type cannot have cases with arguments


enum JPEGCompressionLevel: CGFloat {
    case max = 1
    case high = 0.9
    case med = 0.5
    case low = 0.2
    case custom(CGFloat)
}

I get an error for the custom case:

Enum with raw type cannot have cases with arguments

I would like to use the JPEGCompressionLevel with following syntax:

let a: JPEGCompressionLevel = .custom(0.3)
let b: JPEGCompressionLevel = .max
print(a.rawValue)
print(b.rawValue)

Solution

  • Swift enum can have either raw values or associated values, but not both at the same time. In your case, case max = 1 is a raw value, while custom(CGFloat) is an associated value.

    To overcome this limit, you could use an enum with associated values with a computed property:

    enum JPEGCompressionLevel {
      case custom(CGFloat)
      case max, high, med, low
    
      var value: CGFloat {
        switch self {
        case .max:
          return 1.0
        case .high:
          return 0.9
        case .med:
          return 0.5
        case .low:
          return 0.2
        case .custom(let customValue):
          return customValue
        }
      }
    }
    
    let a: JPEGCompressionLevel = .custom(0.3)
    let b: JPEGCompressionLevel = .max
    
    print(a.value)
    print(b.value)
    

    For more information, you can refer to this article.