首页 > 解决方案 > 原始类型的枚举不能有带参数的案例

问题描述

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

我收到一个错误customEnum 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)

标签: iosswift

解决方案


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)

更多信息,您可以参考这篇文章


推荐阅读