0

Reading the following from NSHipster got me wondering about NSError and if something could be set up so that NSError implicitly converts to a custom error type.

I created the following:

protocol NSErrorConvertible {

    init(error: NSError)
} 

and this

struct CustomError: NSErrorConvertible {
    var message: String
    var code: String?

    init(error: NSError) {
        code = String(error.code)
        message = error.localizedDescription
    }   
}

However, I don't see anything that would make implicit conversion happen.

I know such a feature exists in C++ with a one argument constructor. Is there something available like that in Swift using protocols or something else?

finneycanhelp
  • 9,018
  • 12
  • 53
  • 77

1 Answers1

2

No. Swift generally avoids implicit conversions by design. They even took out the tools we used to use to implement it (__conversion) because it creates a lot of headaches, both for the compiler and by injecting subtle bugs. It is very common that implicit conversion introduces small differences that matter. It is often important that the programmer consider these things and not fall back on magic. This has been a long source of bugs in C and C++.

If you add an _ before the error (so the label isn't required) then explicit conversion is trivial:

init(_ error: NSError) { ... }

...
CustomError(error)

See also Does Swift support implicit conversion?

Community
  • 1
  • 1
Rob Napier
  • 286,113
  • 34
  • 456
  • 610