When will type Error not cast to type NSError?

The sample project CloudKitShare downloaded from developer.apple.com Sharing CloudKit Data with Other iCloud Users has a line of code in HandleCloudKitError.swift that optionally casts an instance of Error to a variable of type NSError.

guard let nsError = error as NSError? else {
    return nil
}

Under what conditions would this fail? I thought this would always succeed.

How do I find out why the cast is unsuccessful? When I put code that prints the type of variable 'error', it seems to always result in Optional like so:

Code:

guard let nsError = error as NSError? else {
    print(type(of: error))
    return nil
}

Optional

What is the purpose of this guard statement?

Under what conditions would this fail?

When error is nil.

I thought this would always succeed.

The cast always succeeds. That’s why it’s an as and not an as?.

This snippet first first the Error? to an NSError?. That can never fail. It then optionally binds that to nsError. That can fail and, if it does, the snippet returns nil.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

When will type Error not cast to type NSError?
 
 
Q