Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum with raw type cannot have cases with arguments

Tags:

ios

swift

enum JPEGCompressionLevel: CGFloat {
    typealias RawValue = CGFloat
    case max = 1, high = 0.9, med = 0.5, low = 0.2, 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)
like image 266
Blazej SLEBODA Avatar asked Dec 17 '19 17:12

Blazej SLEBODA


1 Answers

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.

like image 128
93xrli Avatar answered Nov 13 '22 06:11

93xrli