[swift-evolution] SE-0080: Failable Numeric Conversion Initializers
matthew at anandabits.com
Thu May 5 07:46:30 CDT 2016
Sent from my iPad
> On May 5, 2016, at 2:42 AM, William Shipley via swift-evolution <swift-evolution at swift.org> wrote:
> My quibble with this proposal (which should go through in one form or another) is that the initializers don’t throw.
> I know that this was discussed before, but was this before "try?” was introduced to Swift? Because to me this seems cleaner (with init(exact value: Float) throws)
> let x = try? Int(exact: someFloat)
> Than this (with init?(exact value: Float))
> let x = Int(exact: someFloat)
> Let me be clear I’m not saying no initializers should ever be optional, just that with numeric conversions, it seems like the common case is that we got some bad data, and I like the “try?” syntax for noting, “Hey, this would mean something bad has happened.”
> I also like ‘throws' because it could return something sensible so we could debug the bad input, whereas just returning ‘nil’ doesn’t really tell me why the conversion didn’t occur. In the example given (parsing through a json file) I’d much rather be able to tell the user “Warning, your file is corrupt: 4372498293429387283497824 is too big for your current net worth!” than “ Warning, your file is corrupt: 4372498293429387283497824 is somehow not good enough but I can’t really tell you why.”
This is what the original proposal did and the exact reason why it did things that way (including try? to recover the optional). However, there is a pattern followed by the Apple folks and the standard library that if something can only fail in exactly one obvious way (out of range / not Representable in this case) that it should fail with an optional rather than throwing. I changed the proposal to follow this pattern which will probably also have slightly better performance in cases where the optional is sufficient.
Once the core functionality is present in the standard library it's easy enough to wrap it with something that throws and captures whatever details we require in the process.
> swift-evolution mailing list
> swift-evolution at swift.org
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the swift-evolution