Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - is there a boolean convertible protocol or any other way to overload casting to a custom type?

Tags:

casting

ios

swift

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
}
like image 558
Baptiste Truchot Avatar asked Oct 18 '22 08:10

Baptiste Truchot


1 Answers

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

like image 184
Wilson XJ Avatar answered Oct 21 '22 04:10

Wilson XJ