Failable initializers
When you attempt to initialize an object, it may fail. For example, if you converting a String into an Int there is no guarantee it’ll work.
If you make your own raw representable enumeration type, the compiler will write a
failable initializer for you. To see it at work type in:
enum PetFood: String { case kibble, canned
}
let morning = PetFood.init(rawValue: "kibble") // -> .kibble let snack = PetFood.init(rawValue: "fuuud!") // -> nil
Finally, you can create failable initializers. Try it out:
struct PetHouse { let squareFeet: Int
init?(squareFeet: Int) { if squareFeet < 1 {
return nil
}
self.squareFeet = squareFeet
}
}
let tooSmall = PetHouse(squareFeet: 0) // nil let house = PetHouse(squareFeet: 1) // okay
To make a failable initializer you simply name it init?(...) and return nil if it fails. By using a failable initializer you can guarantee that your instance has the correct attributes or it will never exist.