[swift-evolution] Remove Failable Initializers
Haravikk
swift-evolution at haravikk.me
Thu Mar 3 02:25:25 CST 2016
> On 3 Mar 2016, at 08:07, Patrick Pijnappel via swift-evolution <swift-evolution at swift.org> wrote:
>
> Returning an optional is a simplified form of returning an error when there is only one straightforward way of failing. This is a very common case and is simpler than using an error, for which you need to: 1) call w/ try? 2) add 'throws' to the function 3) return some kind of error instance of some type
How common is it really though? I hardly ever see it come up, but maybe I’m the one doing something unusual?
For me, checking what the return value of an initialiser is is kind of strange to me, as I just expect it to be an instance of whatever type I asked for. Error handling forces you to do something about the possibility of a failure.
> On 2 Mar 2016, at 23:44, Ross O'Brien <narrativium+swift at gmail.com> wrote:
>
> At the risk of appearing glib or naive - which isn't my intention, I'd like to know the answer - is there not a similar argument to be made for any function which returns an optional instead of throwing a more descriptive error? Asking an array for its first element returns an optional because of the possibility it might have no elements in it; should this throw an error instead of being 'failable’?
An optional to me represents something perfectly normal and expected happening that just has no result; i.e- in the case of an array it’s perfectly fine for it to contain no elements, so looking at the first one can’t return a concrete result.
This differs from using a subscript into the array with an invalid index, as with Swift’s index type model you’re not supposed to retain invalid indices into an array that has changed (a lot of the methods of Array specifically state that they disassociate indices with respect to self). So attempting to use a subscript to get an element that doesn’t exist means you’re using an invalid index you shouldn’t have retained, so an error makes sense in that case, vs. returning nil. I admit it’s an easy one to forget since Array indices are just Ints, but they could just as easily be of type ArrayIndex, so you really should limit yourself to index-specific features such as .predecessor(), .successor(), .advancedBy(), .distanceTo() and comparisons with startIndex and endIndex.
I dunno, it’s not a critical thing to change perhaps, but to me a failable/nilable initialiser doesn’t represent a failure as explicitly as error handling does, it also doesn’t force a developer using it to handle that error (even if it’s just to pop a try? in front) or force developer creating it to give a reason why the failure occurred.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160303/243f8c96/attachment.html>
More information about the swift-evolution
mailing list