Failable Init

Introduction

Welcome to Lesson 4 of Object Oriented Swift. You will learn how to design an init method that, first, possibly returns no object, but nil, second, throws an error.

Problem

Can initialization fail?

Error Handling (Review)

Design Error

  1. enum NameError: Error {
  2. case noName
  3. }

Design Struct

  1. struct UdemyCourse {
  2. let courseName: String
  3. init(name: String) throws {
  4. if name.isEmpty {
  5. throw NameError.noName
  6. }
  7. self.courseName = name
  8. }
  9. }

Initialize and Handle Error

  1. do {
  2. let myCourse = try UdemyCourse(name: "Bob")
  3. myCourse.courseName
  4. } catch NameError.noName {
  5. print("Bob, please enter the name")
  6. }

Design Failable Init

Insert ? after the init keyword . It may return nil or an object whose type is optional.

  1. class Blog {
  2. let name: String
  3. init?(name: String) {
  4. if name.isEmpty {
  5. // handle error
  6. return nil
  7. }
  8. self.name = name
  9. }
  10. }
  11. let blog = Blog(name: "") // nil
  12. if let myBlog = blog {
  13. print(myBlog.name)
  14. }

I personally prefer the error-handling approach over failable init due to modularized code and no unwrapping.

Source Code

2004_failable_init.playground

Conclusion

First, you’ve learned how design an init method that may return nil or an optional object by putting a ? right to the init keyword. As we’ve discussed many times, anything that has to do with ? in the Swift Programming Language will give you an optional value. Second, you reviewed the Swift error handling approach. Remember, the throw keyword is not only used within an else-if or guard block, but also within an init method.

In the following lesson, you will learn how to override everything while subclassing.

Note: Learn Swift with Bob is available on Udemy. If you wish to receive a discount link, you may sign up here.