Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return nil in swift in a custom initializer?

Tags:

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

like image 602
zumzum Avatar asked Jun 12 '14 16:06

zumzum


People also ask

Does initializer return any value in Swift?

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.

What is the return type of initializer in Swift?

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 .

What are Failable Initializers in Swift?

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.

What does init () do in Swift?

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.


1 Answers

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() } 
like image 200
user102008 Avatar answered Sep 22 '22 19:09

user102008