[swift-evolution] Remove Failable Initializers

James Campbell james at supmenow.com
Wed Mar 2 15:11:07 CST 2016


Given that we now have error handling and availability checks does it make
sense to have Failable Initializers which date back to Swift 1.1?

Take this model

struct MyModel {

let someProperty
let anotherProperty
}

Lets say we have a Initializers for this structure that takes a JSON
structure and returns an i.

We could guarantee that it always returns an instance but then we have to
populate this data with dummy values if the JSON is missing values.

I could make these properties optional to reflect that the JSON was missing
information but I would be making the structure mutable which adds
complexity. On-top of that I wouldn't be able to tell if the property is
nil due to a lack of a value or a bug causing certain JSON information to
be missing.

So lets look at the alternatives with a non-guranteed system, well we
have Failable Initializers. If any of the properties are missing, we should
return nil.

Well we have this issue:

MyModel(json)

It isn't clear that this is fallable compared to a traditional initializer
unless swift was update to, meaning we may forget to handle the nil case:

 *MyModel?(json)*

This isn't all that is wrong with this approach, if this method does a lot
of steps to create the object and fails (Like parsing an object from JSON).
Returning nil but we have no idea why, it makes it easy to introduce
silently failing errors.

Its true some classes may do this when ran on a older version of iOS but
with avaliabilty checks, this use case is irrelevant.

So what about throwing an error?

It forces us to handle it failing to initialize for some reason.

- If we forget to handle the error, the app won't be allowed to continue
with this corrupted data - and the error will be informative as it forces
us to create an ErrorType.
- If we want to ignore this object and convert the error to nil we can
still use *try? *(For example in a Chat application you could ignore
corrupted messages).
- In these cases where we ignore the error using *try?* it makes it super
obvious we are ignoring an error and it should be easy to that error
causing it to fail by using *try! *
- On the whole it encourages us to not return nil and to return useful
error codes which we can handle, what if one of the reasons it failed to
parse is something we could recover from? If we return nil we will never
know.
- And it reduces the amount of mutability in swift.


*___________________________________*

*James⎥Head of Trolls*

*james at supmenow.com <james at supmenow.com>⎥supmenow.com <http://supmenow.com>*

*Sup*

*Runway East *

*10 Finsbury Square*

*London*

* EC2A 1AF *
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160302/f575e60a/attachment.html>


More information about the swift-evolution mailing list