Errors
Implementation
Enum based
The simplest approach is probably to define one custom enum
with just one case
that has a String
attached to it:
enum MyError: Error {
case runtimeError(String)
}
extension MyError: LocalizedError {
var errorDescription: String? {
switch self {
case .runtimeError(let str):
"RunTime Error: \(str)"
}
}
}
Example usage would be something like:
func someFunction() throws {
throw MyError.runtimeError("some message")
}
do {
try someFunction()
} catch MyError.runtimeError(let errorMessage) {
print(errorMessage)
}
If you wish to use existing Error
types, the most general one would be an NSError
, and you could make a factory method to create and throw one with a custom message.
Struct based
Or use another approach
struct RuntimeError: LocalizedError {
let description: String
init(_ description: String) {
self.description = description
}
var errorDescription: String? {
description
}
}
And to use:
throw RuntimeError("Error message.")