Raw type 'Bool' is not expressible by any literal
my solution on swift 3
enum DataType: RawRepresentable {
case given
case received
typealias RawValue = Bool
var rawValue: RawValue {
return self == .given ? true : false
}
init?(rawValue: RawValue) {
self = rawValue == true ? .given : .received
}
}
Swift 3 natively defines those nine literal representations:
- ExpressibleByNilLiteral (
nil
) - ExpressibleByBooleanLiteral (
false
) - ExpressibleByArrayLiteral (
[]
) - ExpressibleByDictionaryLiteral (
[:]
) - ExpressibleByIntegerLiteral (
0
) - ExpressibleByFloatLiteral (
0.0
) - ExpressibleByUnicodeScalarLiteral (
"\u{0}"
) - ExpressibleByExtendedGraphemeClusterLiteral (
"\u{0}"
) - ExpressibleByStringLiteral (
""
)
But enum
raw representation will apparently only accept natively the subset of those representions that start with a digit (0
-9
), a sign (-
, +
) or a quote ("
): the last five protocols of above list.
In my opinion, the error message should have been more specific. Maybe something explicit like that would have been nice:
Raw type 'Bool' is not expressible by any numeric or quoted-string literal
Extending Bool to conform to one of those protocols is still possible, for example:
extension Bool: ExpressibleByIntegerLiteral {
public init(integerLiteral value: Int) {
self = value != 0
}
}
And after doing so, this code now builds fine:
enum TopBarStyle: Bool {
case darkOnLight
case lightOnDark
}
@IBInspectable var style = TopBarStyle(rawValue: false)!
Simplify your life:
enum TopBarStyle {
case darkOnLight
case lightOnDark
var bool: Bool {
switch self {
case .darkOnLight:
return true
default:
return false
}
}
}
Use as usual:
var current = TopBarStyle.darkOnLight
if current.bool {
// do this
} else {
// do that
}
You can extend cases to more but they are not reversible since its an N : 2 matrix