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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With