Swift Language Initializers Throwable Initilizer

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

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 { 
           ValidationError.invalid
        }

        self.name = name
    }
}

Now, you can use throwable initializer by:

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


Got any Swift Language Question?