How to return nil in swift in a custom initializer?

zumzum picture zumzum · Jun 12, 2014 · Viewed 19.7k times · Source

I am trying to write a custom initializer in swift. I have something like this:

convenience init(datasource:SomeProtocol) {
    assert(datasource != nil, "Invalid datasource")
    if(datasource == nil) {
        return nil
    }
    self.init()
}

The "return nil" line gives me this error: "could not find an overload for '__conversion' that accepts the supplied arguments"

So, all I am trying to accomplish is to have this convenience initializer to return nil if the caller does not provide a valid datasource.

What am I doing wrong here?

Thanks

Answer

user102008 picture user102008 · Sep 15, 2014

Update: Starting in Xcode 6.1 beta 1 (available in the Mac Dev Center), Swift initializers can be declared to return an optional:

convenience init?(datasource:SomeProtocol) {
    if datasource == nil {
        return nil
    }
    self.init()
}

or an implicitly-unwrapped optional:

convenience init!(datasource:SomeProtocol) {
    if datasource == nil {
        return nil
    }
    self.init()
}