Swift Language Initializers Throwable Initilizer


Using Error Handling to make Struct(or class) initializer as throwable initializer:

Example Error Handling enum:

enum ValidationError: Error {
    case invalid

You can use Error Handling enum to check the parameter for the Struct(or class) meet expected requirement

struct User {
    let name: String

    init(name: String?) throws {

        guard let name = name else { 

        self.name = name

Now, you can use throwable initializer by:

do {
   let user = try User(name: "Sample name")
   // success
catch ValidationError.invalid {
     // handle error