swiftios8

Proper way to handle a fail to init


I am looking for a proper way to handle a invalid argument during a initialization.

I am unsure how to do it using Swift as the init has't a return type. How can I tell whoever is trying to initialize this class that you are doing something wrong?

init (timeInterval: Int) {
    if timeInterval > 0
        self.timeInterval = timeInterval
    else
        //???? (return false?)
}

Thank you!


Solution

  • Use a failable initializer. Such an initializer looks very similar to a regular designated initializer, but has a '?' character right after init and is allowed to return nil. A failable initializer creates an optional value.

    struct Animal {
        let species: String
        init?(species: String) {
            if species.isEmpty { return nil }
            self.species = species
        }
    }
    

    See Apple's documentation on failable initializers for more detail.