[swift-evolution] Nil-rejection operator
John McCall
rjmccall at apple.com
Fri Feb 17 00:30:34 CST 2017
> On Feb 16, 2017, at 9:45 PM, Jon Shier via swift-evolution <swift-evolution at swift.org> wrote:
> I created this set of extensions so I could more easily deal with optionals in a context where I was already potentially throwing errors.
>
> extension Optional {
>
> func deoptionalize() throws -> Wrapped {
> switch self {
> case .some(let wrapped): return wrapped
> case .none: throw "\(self.self) was nil."
> }
> }
>
> }
>
> extension String: LocalizedError {
>
> public var localizedDescription: String {
> return self
> }
>
> }
>
> It’s probably a bad idea to make String an Error, but it worked.
Yeah, this seems reasonable (although you might consider making some earlier part throw the error instead of returning an optional?) except for the completely unnecessary use of String as the error type. Just make a new error enum with one case; it'll be much easier to recognize it if you need to.
Also, I'm pretty sure that that string is always going to expand to "nil was nil."
John.
> It seems to me like there should be something more convenient for dealing with Optionals in contexts where unwrapping them is awkward.
>
>
>
> Jon
>
>
>> On Feb 9, 2017, at 5:35 PM, Rob Mayoff via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> wrote:
>>
>> On Thu, Feb 9, 2017 at 2:25 PM, Haravikk via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> wrote:
>> I wonder if an alternative to the original proposal might be to allow throw on the right hand side? So you could do:
>>
>> let y = x ?? throw myError
>>
>>
>> You can do this today:
>>
>> extension Error {
>> func throwMe<R>() throws -> R { throw self }
>> }
>>
>> let y = try x ?? MyError().throwMe()
>>
>> _______________________________________________
>> swift-evolution mailing list
>> swift-evolution at swift.org <mailto:swift-evolution at swift.org>
>> https://lists.swift.org/mailman/listinfo/swift-evolution
>
> _______________________________________________
> 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/20170217/f6a19ffc/attachment.html>
More information about the swift-evolution
mailing list