[swift-evolution] Nil-rejection operator

Jon Shier jon at jonshier.com
Thu Feb 16 20:45:59 CST 2017


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. 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> 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
> https://lists.swift.org/mailman/listinfo/swift-evolution

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170216/2b85ccc2/attachment.html>


More information about the swift-evolution mailing list