Is there a reason that a throwing unwrap function/operator isn’t part of the 
standard library? Seems like it would be handy to be able to have a one-liner 
for attempting to unwrap and throw if it’s nil. Something like


postfix operator .?!

extension Optional {
        static postfix func .?!(optional: Optional<Wrapped>) throws -> Wrapped {
                switch optional {
                case let .some(wrapped):
                        return wrapped
                case .none:
                        throw UnwrapError()
                }
        }
}

init?(data: [String: Any]) {
        do {
                self.someProperty = try data["some_key”].?!
                self.anotherProperty = try data["another_key”].?!
        } catch is UnwrapError {
                return nil
        }
}


> On Jul 26, 2017, at 12:13 PM, Chris Lattner via swift-evolution 
> <[email protected]> wrote:
> 
> 
>> On Jul 25, 2017, at 2:44 AM, philohan95 via swift-evolution 
>> <[email protected]> wrote:
>> 
>> I think the current way to initiate models in a Failable Initializer 
>> `init?()` is overly verbose and should be shortened down so less boilerplate 
>> should be needed.
>> 
>> The current way:
>> 
>> ```
>> let someProperty: Any
>> let anotherProperty: Any
>> 
>> init?(data: [String: Any]) {
>>      guard
>>              let someProperty = data["some_key"],
>>              let anotherProperty = data["another_key"]
>>      else {
>>              return nil
>>      }
>> 
>>      self. someProperty = someProperty
>>      self. anotherProperty = anotherProperty
>> }
>> ```
> 
> Guard isn’t really the right answer for this, I’d try something like this 
> (where unwrapOrThrow is the obvious generic function you can define yourself):
> 
> init?(data: [String: Any]) {
>       do {
>               self.someProperty = try unwrapOrThrow(data["some_key”])
>               self.anotherProperty = try unwrapOrThrow(data["another_key”])
>       } catch {
>               return nil
>       }
> }
> 
> -Chris
> 
> _______________________________________________
> swift-evolution mailing list
> [email protected]
> https://lists.swift.org/mailman/listinfo/swift-evolution

_______________________________________________
swift-evolution mailing list
[email protected]
https://lists.swift.org/mailman/listinfo/swift-evolution

Reply via email to