Optionals

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Open the Lesson01-Review-Basics playground. Start on the Lesson01-optionals page.

Failable Initializers

Some Swift standard types have initializers that can fail, so their return type is an optional. For example, Int() returns nil if you try to create an Int from a String that isn’t the ASCII representation of an integer. Run these two lines of code:

Optional Chaining

Many people own pets — but not all. Some pets have a favorite toy, and others don’t. Some of these toys make noise, and others don’t. Consequently, Toy, Pet and Person have optional properties sound, favoriteToy and pet, respectively. Run the following code to create three Person objects:

Kufqus olpavgm
Sehtey ohdayhl

Maetp ag cigoviye xic uk vom
Roavt ex pujifisi lah ob gew

See forum comments
Download course materials from Github
Previous: Introduction Next: Throw-Catch