I created an enum which mimics a boolean, and I would like to be able to automatically cast real booleans to this custom type.
It's possible to do it for literal boolean thanks to the BooleanLiteralConvertible protocol (see below).
Is there an equivalent protocol for non literal boolean? Or is there a way to overload the as? operator ?
enum CustomType {
case True
case False
}
extension CustomType : BooleanLiteralConvertible {
init(booleanLiteral value: BooleanLiteralType) {
if value {
self = .True
} else {
self = .False
}
}
}
func def(a: CustomType) {
}
func test() {
let a : Bool = true
def(true) // compiles
def(a) // does not compile
}
maybe protocol BooleanType
can help you ,try to implement it like this:
enum CustomType :BooleanType{
var boolValue: Bool {
switch self {
case .True:
return true
case .False:
return false
}
}
case True
case False
init(bool:Bool){
self = bool ? .True : .False
}
}
then you can use :
let myTrue = true
let trueType = CustomType(bool: myTrue)
if trueType {
print("hello world")
}
note: LiteralConvertible
protocols are only made for Literal conversion
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With