Simplest way to throw an error/exception with a custom message in Swift 2?
The simplest approach is probably to define one custom enum
with just one case
that has a String
attached to it:
enum MyError: ErrorType {
case runtimeError(String)
}
Or, as of Swift 4:
enum MyError: Error {
case runtimeError(String)
}
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.
The simplest way is to make String
conform to Error
:
extension String: Error {}
Then you can just throw a string:
throw "Some Error"
To make the string itself be the localizedString
of the error you can instead extend LocalizedError
:
extension String: LocalizedError {
public var errorDescription: String? { return self }
}
@nick-keets's solution is most elegant, but it did break down for me in test target with the following compile time error:
Redundant conformance of 'String' to protocol 'Error'
Here's another approach:
struct RuntimeError: Error {
let message: String
init(_ message: String) {
self.message = message
}
public var localizedDescription: String {
return message
}
}
And to use:
throw RuntimeError("Error message.")