Throwable initializer
suggest changeError handling can make a struct or class initializer throw:
enum ValidationError: Error {
case invalid
}
Throw when the argument does not meet the requirement:
struct User {
let name: String
init(name: String?) throws {
guard let name = name else {
throw ValidationError.invalid
}
self.name = name
}
}
Call the initializer with try:
do {
let user = try User(name: "Sample name")
// success
}
catch ValidationError.invalid {
// handle error
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents