[swift-evolution] Proposal: allow delegating from a throwing initializer to a failable initializer

Matthew Johnson matthew at anandabits.com
Sat Dec 12 21:55:30 CST 2015

It is not currently possible to call a failable (optional) initializer from a throwing initializer.  This is unfortunate as many Cocoa initializers are failable and it is desirable to be able to extend Cocoa types with throwing convenience initializers that call a failable (optional) designated initializer.

For example, something similar to the following should be possible:

enum CustomError: ErrorType { case E }

struct S {
    let urlString: String

extension NSURL {
    convenience init(s: S) throws {
        guard self.init(string: s.urlString)
            else { throw CustomError.E }

In the current language, even if the compiler preventing us from calling the failable initializer we would not be able to access the return value in the guard expression.  Furthermore, even if we could an Optional expression would not be valid in a guard condition.  I am interested in ideas for how this should be handled.  Would there be a special case of the guard statement to allow this?  Or should some other mechanism be used to guarantee that we either successfully complete initialization or throw?

As an aside, the term ‘failable initializer’  implies to me any initializer that can fail, whether by returning an optional or by throwing.  I think it would be best if we adopt more precise terminology to refer to ‘optional initializers’ and ‘throwing initializers’.  I welcome any feedback on this idea.


More information about the swift-evolution mailing list