Throwable initializer

suggest change

Error 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
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents