O'Reilly logo

Mastering Swift 4 - Fourth Edition by Jon Hoffman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Failable initializers

A failable initializer is an initializer that may fail to initialize the resources needed for a class or a structure, thereby rendering the instance unusable. When using a failable initializer, the result of the initializer is an optional type, containing either a valid instance of the type or nil.

An initializer can be made failable by adding a question mark (?) after the init keyword. Let's look at how we can create a failable initializer that will not allow a new employee to be initialized with a salary of less than $20,000 a year:

init?(firstName: String, lastName: String, salaryYear: Double) { self.firstName = firstName self.lastName = lastName self.salaryYear = salaryYear if self.salaryYear < 20_000 { return nil ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required