[swift-evolution] [Accepted] SE-0112: Improved NSError Bridging

Kevin Ballard kevin at sb.org
Fri Aug 5 21:10:44 CDT 2016


> On Aug 5, 2016, at 5:16 PM, Erica Sadun <erica at ericasadun.com> wrote:
> 
> 
>> On Aug 5, 2016, at 4:19 PM, Douglas Gregor via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> wrote:
>> 
>>> 
>>> On Aug 5, 2016, at 12:59 PM, Kevin Ballard via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> wrote:
>>> 
>>> If all you want to do is get the localized description, then you can just say `(error as NSError).localizedDescription`.
>> 
>> Just ‘error.localizedDescription’ works now. That was part of SE-0112.
>> 
>> 	- Doug
> 
> Would it kill to allow:
> 
> let err = NSError()
> err.localizedDescription = "bad things happen"
> throw err
> 
> or even
> 
> throw NSError("Bad things happen")
> 
> for lightweight use? I ended up refactoring entirely to enum : Error because Swift yelled at me for using NSError(): "this results in an invalid NSError instance. It will raise an exception in a future release. Please call errorWithDomain:code:userInfo: or initWithDomain:code:userInfo:. This message shown only once."
> 
> enum Errors: Error {case bad}
> Errors.bad._code // 0
> Errors.bad._domain // "Errors"
> Errors.bad._userInfo // Optional({})
> Errors.bad.localizedDescription // "The operation couldn’t be completed. (Errors error 0.)"
> 
> Bleh.

NSErrors need a domain/code. It doesn’t make much sense to throw one without it. And besides, there’s a fairly trivial solution for doing what you want to do:

struct GenericError: LocalizedError {
    let message: String
    init(_ message: String) {
        self.message = message
    }
    var errorDescription: String? {
        return message
    }
}

Now you can just say `throw GenericError(“Bad things happen”)`.

-Kevin Ballard
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160805/c6ed7f58/attachment.html>


More information about the swift-evolution mailing list