Skip to content

[Office Hours] is throwing in an initializer bad style, or does it depend? #93

Discussion options

You must be logged in to vote

Hi @kkellybonilla,

It's not inherently bad practice for an initializer to throw an error. If you have a situation where an invalid argument would stop you from creating the object and/or crash your app, there is no reasonable default value, and you want the caller to understand exactly what happened and handle the failure explicitly, then throwing an error from the initializer makes sense. Here's how you might write that for your car example:

struct Car {
   let model: String
   let currentGear: Int
   
   init(model: String, currentGear: Int) throws {
       guard (1...10) ~= currentGear else {
           throw CarError.invalidGear(currentGear)
       }
       self.model = model
       self

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@kkellybonilla
Comment options

kkellybonilla Jan 12, 2025
Collaborator Author

Answer selected by kkellybonilla
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants