enum JPEGCompressionLevel: CGFloat {
case max = 1
case high = 0.9
case med = 0.5
case low = 0.2
case custom(CGFloat)
}
我收到
custom
案例的错误:
原始类型的枚举不能有带参数的情况
我想使用以下语法的 JPEGCompressionLevel:
let a: JPEGCompressionLevel = .custom(0.3)
let b: JPEGCompressionLevel = .max
print(a.rawValue)
print(b.rawValue)
Swift
enum
可以具有原始值或关联值,但不能同时具有两者。在您的情况下, case max = 1
是原始值,而 custom(CGFloat)
是关联值。
要克服此限制,您可以使用
enum
以及具有计算属性的关联值:
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)
欲了解更多信息,您可以参考这篇文章。