[swift-evolution] Remove Failable Initializers

Haravikk swift-evolution at haravikk.me
Wed Mar 9 05:18:51 CST 2016


> On 9 Mar 2016, at 10:32, Tino Heth via swift-evolution <swift-evolution at swift.org> wrote:
> 
> As ease of use and performance implications have been discussed, I would still like to see the question of consistency addressed:
> In Objective-C, returning nil from an initializer is nothing special — it is a regular function that returns id (self in most cases).
> 
> Swift, on the other hand, is different:
> Init-methods are void-functions in every aspect, with the irregularity that we can return "nil" (if the initializer is marked accordingly).
> 
> Am I the only one who has the feeling that this is a little bit odd?
> What kind of method is a initializer in Swift?

A related consideration to this is that we have no choice in how initialisers are named. For example, a method named “search” is pretty clear that it will look for something, but places no guarantee that a result will actually be found, which means that it’s fairly logical that it has an optional return type vs an error (since finding nothing isn’t an error, just one of the possible outcomes).

Initialisers meanwhile are really named for the type they belong to; though we can use more descriptive parameter names I suppose to give the implication of optionality, it can still be messy when you’re dealing with a mixture of regular and failable initialisers that all look very similar. Requiring a trailing question mark to indicate optionality at the call site would partially address this, though the feature still seems redundant to me.

> On 9 Mar 2016, at 06:23, Thorsten Seitz <tseitz42 at icloud.com> wrote:
> 
> If I have a simple case where I just want to skip failed initializations the errors won't help me anything in unexpected cases because I disregarded them anyway.

You can only guarantee that they’ll be universally disregarded if you’re talking about an internal or private type, in which case you could just as easily throw anything you like if you know you’re never going to actually use it; personally I’d still try to throw something semi-useful, even if it just ends functioning as a useful reminder it’s better than nothing.

In terms of maintainability it can also be useful to other developers even if they have access to the source code of your initialiser, as instead of having to dig into that to find out what’s wrong they can try inspecting the error first to see if that helps; I don’t think we can currently access the error that was thrown into a try? statement, but if the debugger could do this it’d be even easier.


More information about the swift-evolution mailing list