enum MyBool {
case myTrue, myFalse
}
/// A value type whose instances are either `true` or `false`.
extension MyBool {
/// Default-initialize Boolean value to `true`.
init(){ self = .myTrue }
}
extension MyBool : BooleanLiteralConvertible {
static func convertFromBooleanLiteral( value: Bool) -> MyBool {
return value ? myTrue : myFalse
}
}
extension MyBool : BooleanType {
var boolValue: Bool {
switch self {
case .myTrue: return true
case .myFalse: return false
}
}
}
extension MyBool {
// MyBool can be constructed from BooleanType
init(_ v : BooleanType) {
if v.boolValue {
self = .myTrue
} else {
self = .myFalse
}
}
}
问题是mybool不符合协议BooleanLiteralConvertible。 任何人都可以指出我正确的方向。
答案 0 :(得分:0)
符合BooleanLiteralConvertible
要求添加一个接受BooleanLiteralType
又称Bool
的初始值设定项。您的示例的略微修改版本符合BooleanLiteralConvertible
和BooleanType
:
enum MyBool: BooleanLiteralConvertible, BooleanType {
case myTrue
case myFalse
var boolValue: Bool {
return self == .myTrue
}
init() {
self = .myTrue
}
init(booleanLiteral value: Bool) {
self = value ? .myTrue : .myFalse
}
}