Raw type ‘Bool’ is not expressible by any literal
我想让我的枚举与 @IBInspectable 轻松兼容,所以为了简单起见,我尝试让它可以用类型 Bool:
表示
|
1
2 3 4 |
enum TopBarStyle: Bool {
case darkOnLight case lightOnDark } |
但是 Xcode 给了我:
Raw type ‘Bool’ is not expressible by any literal
这很奇怪,因为 true 和 false 似乎是文字表达能力的完美候选者。
我还尝试将 RawRepresentable 一致性添加到 Bool 类型:
|
1
2 3 4 5 6 7 8 |
extension Bool: RawRepresentable {
public init?(rawValue: Bool) { self = rawValue } public var rawValue: Bool { get { return self } } } |
但它并没有解决错误。
- 文档非常清楚:developer.apple.com/library/content/documentation/Swift/…:”原始值可以是字符串、字符或任何整数或浮点数类型。
- 您可以通过在枚举上添加计算的 var boolValue 来实现相同的效果。
- 添加到@MartinR 的评论中, true 和 false 不是文字;它们更接近常量(名称由编译器保留的常量)。文字是编译器有一些魔法可以转换为内部值的东西。理解 true 和 false 不需要任何魔法,因为它们是关键字。
Swift 3 原生定义了这九种文字表示:
- ExpressibleByNilLiteral (nil)
- ExpressibleByBooleanLiteral (false)
- ExpressibleByArrayLiteral ([])
- ExpressibleByDictionaryLiteral ([:])
- ExpressibleByIntegerLiteral (0)
- ExpressibleByFloatLiteral (0.0)
- ExpressibleByUnicodeScalarLiteral (“\\u{0}”)
- ExpressibleByExtendedGraphemeClusterLiteral (“\\u{0}”)
- ExpressibleByStringLiteral (“”)
但 enum 原始表示显然只接受以数字 (0-9)、符号 (-, +) 或引号 (“): 上面列表的最后五个协议。
在我看来,错误信息应该更具体。也许像这样明确的东西会很好:
Raw type ‘Bool’ is not expressible by any numeric or quoted-string literal
扩展 Bool 以符合其中一种协议仍然是可能的,例如:
|
1
2 3 4 5 |
extension Bool: ExpressibleByIntegerLiteral {
public init(integerLiteral value: Int) { self = value != 0 } } |
在这样做之后,这段代码现在构建得很好:
|
1
2 3 4 5 6 |
enum TopBarStyle: Bool {
case darkOnLight case lightOnDark } @IBInspectable var style = TopBarStyle(rawValue: false)! |
我在 swift 3 上的解决方案
|
1
2 3 4 5 6 7 8 9 10 11 12 |
enum DataType: RawRepresentable {
case given case received typealias RawValue = Bool |
- 有趣的。所以 extension Bool: RawRepresentable enum DataType: Bool 不起作用,但直接 enum DataType: RawRepresentable 会起作用。
- 请注意,此处不需要 typealias。
- 请注意,这一行(return self == .given ? true : false)将导致递归。所以请改用开关盒。
我不认为这是必要的。你可以只做一个普通的枚举,然后切换它的案例。此外,完全不清楚 TopBarStyle(rawValue: true) 如果可以实现这将意味着什么。
我会使用 var darkOnLight: Bool 或 enum TopBarStyle { /*cases*/ } 并根据需要切换大小写。
简化你的生活:
|
1
2 3 4 5 6 7 8 9 10 11 12 13 |
enum TopBarStyle {
case darkOnLight case lightOnDark var bool: Bool { |
照常使用:
|
1
2 3 4 5 6 7 |
var current = TopBarStyle.darkOnLight
if current.bool { |
您可以将案例扩展到更多,但它们是不可逆的,因为它是一个 N : 2 矩阵
- 这不会使它与 @IBInspectable 兼容。因此,在这方面,接受的答案更有帮助。
- 当 swift RawRepresentable 为您提供灵活性时,为什么要使用 Extra ‘.bool’。
- 我重新创建了它以使我更容易访问某些预定义的 SCNVector3 值。超级好答案!
来源:https://www.codenong.com/42292197/
