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
You implement this initialization process by defining initializers, which are like special methods that can be called to create a new instance of a particular type. Unlike Objective-C initializers, Swift initializers don't return a value.
IMPORTANT: In swift, the initializers won't return anything. But objective -C does. In swift, You write return nil to trigger an initialization failure, you do not use the return keyword to indicate initialization success. Example: We have a failable initializer for converting Double to Int .
It makes sense sometimes not to return an object if the initialization of one or more properties that play crucial role in the type does not succeed. A failable initializer in Swift is an initializer that allows to do that, as it can potentially return nil if one or more conditions are not satisfied.
Swift init() Initialization is the process of preparing an instance of a class, structure, or enumeration for use. This process involves setting an initial value for each stored property on that instance and performing any other setup or initialization that is required before the new instance is ready for use.
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() }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With