[swift-evolution] Idea: Properties in Failable Initializers less verbose
Taylor Swift
kelvin13ma at gmail.com
Tue Jul 25 17:26:15 CDT 2017
Catching and throwing exceptions is not the same as a controlled guard
fail. It’s also quite verbose and requires extra types to be defined
outside the scope of the initializer.
On Tue, Jul 25, 2017 at 5:35 PM, Rob Mayoff via swift-evolution <
swift-evolution at swift.org> wrote:
> On Tue, Jul 25, 2017 at 4:44 AM, philohan95 via swift-evolution <
> swift-evolution at swift.org> wrote:
>
>> As you can see we had to use the properties twice (this would also be the
>> case of `if let`) making the initializer twice as long as necessary and
>> becomes a pain to implement when having more than 1 property.
>>
>
>> My idea is extending the power of the `guard` statement
>>
>> Idea:
>> init?(data: [String: Any]) {
>> guard
>> someProperty = data["some_key"], // Currently
>> fails because `self` us used before all stored properties are initialized
>> anotherProperty = data["another_key"]
>> else {
>> return nil
>> }
>> }
>> }
>>
>
> I'm not convinced new syntax is necessary. You can get pretty close to
> this today. First, put this in your project somewhere:
>
> struct NilError: Error { }
>
> func throwNilError<Whatever>() throws -> Whatever {
> throw NilError()
> }
>
> Then use do/try/catch to initialize your properties:
>
> class MyObject {
> let someProperty: Any
> let anotherProperty: Any
>
> init?(data: [String: Any]) {
> do {
> someProperty = try data["some_key"] ?? throwNilError()
> anotherProperty = try data["another_key"] ?? throwNilError()
> } catch {
> return nil
> }
> }
> }
>
> It also works for Charles Srstka's example:
>
> let bar: String
> if someCondition {
> do { bar = mightReturnOptional() ?? throwNilError() }
> catch { return }
> } else {
> bar = wontReturnOptional()
> }
>
>
>
>
>
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170725/9df14cfa/attachment.html>
More information about the swift-evolution
mailing list