Baptiste Truchot Baptiste Truchot - 1 year ago 66
iOS Question

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

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

Answer Source

There were features to support things like this in early versions of Swift and they were intentionally removed. Swift typically avoids implicit type conversions. They tend to explode compile times, and often lead to unexpected and undesired conversions. The current implicit conversion from T to T? is a common source of confusing compiler errors and incorrect overload calls in generic code. Building more things like that without many more changes to the Swift compiler is problematic. Even implicit numeric conversions, which the Swift team has expressed as desirable in principle, are not currently possible due to these problems and you need to explicitly convert.

The preferred way is to define an explicit overload in cases where it is useful:

func def(a: Bool) { def(CustomType(a)) }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download