Accessing code in Swift 3 Error

Another option to access code and domain properties in Swift 3 Error types is extending it as follow:

extension Error {
    var code: Int { return (self as NSError).code }
    var domain: String { return (self as NSError).domain }
}

Now in Xcode 8 and swift 3 the conditional cast is always succeeds, so you need do following:

let code = (error as NSError).code

and check the code for your needs. Hope this helps


Casting to SKError seems to be working for me in xCode 8 and Swift 3...

    guard let error = transaction.error as? SKError else {return}
    switch error.code {  // https://developer.apple.com/reference/storekit/skerror.code
    case .unknown: break
    case .paymentCancelled: break
    case .clientInvalid: break
    case .paymentInvalid: break
    case .paymentNotAllowed: break
    case .cloudServiceNetworkConnectionFailed: break
    case .cloudServicePermissionDenied: break
    case .storeProductNotAvailable: break
    }

No need for rawValue.


This is correct (Apple's own tests use this approach):

if error._code == SKError.code.paymentCancelled.rawValue { ... }

On the other hand, casting to NSError will probably be deprecated soon:

let code = (error as NSError).code // CODE SMELL!!
if code == SKError.code.paymentCancelled.rawValue { ... }

Use

error._code == NSURLErrorCancelled

to match the error code.