ios - 原始类型的枚举不能有带参数的案例
问题描述
enum JPEGCompressionLevel: CGFloat {
typealias RawValue = CGFloat
case max = 1, high = 0.9, med = 0.5, low = 0.2, custom(CGFloat)
}
我收到一个错误custom
:Enum with raw type cannot have cases with arguments
我想使用具有以下语法的 JPEGCompressionLevel:
let a: JPEGCompressionLevel = .custom(0.3)
let b: JPEGCompressionLevel = .max
print(a.rawValue)
print(b.rawValue)
解决方案
Swiftenum
可以具有原始值或关联值,但不能同时具有两者。在您的情况下,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)
更多信息,您可以参考这篇文章。
推荐阅读
- javascript - 为什么在中间件中的“调度动作”之后没有保存“状态Vuex”
- java - 为什么我们在 java 中读取 JSON 文件或请求对象时使用以下代码?
- arrays - Ruby,Array.select 元素数量
- google-apps-script - 如何在谷歌表格的应用程序脚本中引用行而不是列?
- keras - keras 多输入模型:预计会看到 2 个数组,但得到了以下 1 个数组的列表
- angular - 如何解决angular app中的clearance-icons.min.js版本冲突
- python - 在 Python 中组合正则表达式 - \W 和 \S
- ruby-on-rails - Rails 说在尝试创建提交时任务必须存在
- vba - 无法在 VBA 中使用 ADODB 选择 .csv 的第一列
- latex - 重新定义 \footnote 以更改 Latex 中索引的颜色