iosswiftconvenience-methods

How to return nil in swift in a custom initializer?


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


Solution

  • It's because initializers actually don't have return any value. You can't return nil if a method don't expect a return type.

    To achieve what you are trying to do (i.e. force your class to have a datasource), just make your datasource not an optional. Variables that are not optional must have a value (so cannot be nil) and must be initialized.