Last active
April 1, 2021 01:58
-
-
Save yosshi4486/db71119e75f82ce3af943d7b67c037a9 to your computer and use it in GitHub Desktop.
What happen when casting Swift.Error or Swift.LocalizedError to NSError?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Try them in Playground file. | |
/* Background when executing cast(swiftError as NSError) | |
1. NSError uses Swift.Error type name as its `domain` property. | |
2. NSError uses a eumeration number as its `code` property. | |
*/ | |
import UIKit | |
enum SwiftError: Error { | |
case busyNetwork | |
case clientProblem | |
case serverProblem | |
} | |
let busyNetworkNSError = SwiftError.busyNetwork as NSError | |
print("domain: \(busyNetworkNSError.domain)") | |
print("code: \(busyNetworkNSError.code)") | |
print("localizedDescription: \(busyNetworkNSError.localizedDescription)") | |
print("localizedFailureReason: \(busyNetworkNSError.localizedFailureReason)") | |
print("localizedRecoverySuggestion: \(busyNetworkNSError.localizedRecoverySuggestion)") | |
/* Result. NSError provides default localizedDescription "The operation couldn’t be completed \(domain) \(code)" | |
domain: __lldb_expr_22.SwiftError | |
code: 0 | |
localizedDescription: The operation couldn’t be completed. (__lldb_expr_22.SwiftError error 0.) | |
localizedFailureReason: nil | |
localizedRecoverySuggestion: nil | |
*/ | |
enum SwiftLocalizedError: LocalizedError { | |
case busyNetwork | |
case clientProblem | |
case serverProblem | |
var failureReason: String? { | |
return "The client machine is angry." | |
} | |
var recoverySuggestion: String? { | |
return "Apologize to the machine" | |
} | |
} | |
let clientProblemLocalizedNSError = SwiftLocalizedError.clientProblem as NSError | |
print("domain: \(clientProblemLocalizedNSError.domain)") | |
print("code: \(clientProblemLocalizedNSError.code)") | |
print("localizedDescription: \(clientProblemLocalizedNSError.localizedDescription)") | |
print("localizedFailureReason: \(clientProblemLocalizedNSError.localizedFailureReason)") | |
print("localizedRecoverySuggestion: \(clientProblemLocalizedNSError.localizedRecoverySuggestion)") | |
/* Result. NSError uses localizedFailureReason in localizedDescription "The operation couldn’t be completed \(localizedFailureReason))" | |
domain: __lldb_expr_26.SwiftLocalizedError | |
code: 1 | |
localizedDescription: The operation couldn’t be completed. The client machine is angry. | |
localizedFailureReason: Optional("The client machine is angry.") | |
localizedRecoverySuggestion: Optional("Apologize to the machine") | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment