Optionals
Lesson 1 of 1
  1. 1
    Sometimes when we work with data, we find that information is missing. Let’s imagine that you are writing a program that displays the first letter of a user’s middle name. let firstName = “Frankl…
  2. 2
    Optional types either contain a value or nil. An optional type is defined with a question mark: var firstLetter: Character? Optionals can be assigned to either nil or an instance of the optiona…
  3. 3
    Once you’ve created an optional, you’ll want to be able to access the value inside. However, if you just try to use the optional, you will get a compile-time error: var a = 4 var b: Int? = 3 let …
  4. 4
    In the last exercise, we saw that force unwrapping allows us to access the underlying value of an optional, but can crash our program if the value is nil. Wouldn’t it be great if we could access o…
  5. 5
    if let statements are a great way to safely handle optional values. Sometimes, we might have a lot of optionals we need to unwrap! This can get very indented: var a: Int? = 1 var b: Int? = 2 var…
  6. 6
    Guard statements give us another way to avoid overly nested code. A guard statement has the following form: func greetUser(isAuthenticated: Bool) { guard isAuthenticated else { prin…
  7. 7
    The nil-coalescing operator gives us another way to handle optional values by allowing us to provide a default value if the optional is nil. nil-coalescing uses the syntax optionalVal ?? defau…
  8. 8
    It’s common in Swift to chain properties and method calls on a variable: let instrument = “piano” let firstUppercasedCharacter = instrument.uppercased().first print(firstUppercasedCharacter) // pr…
  9. 9
    Because optionals are types just like Arrays and Strings are, we can use them in the signature of a function. Optionals are useful because when writing some functions, you might not have a good va…
  10. 10
    Great work! By using optionals, you can make sure to handle values that might be nil. A value might be nil because the user didn’t provide a response. A value might also be nil because we might …

What you'll create

Portfolio projects that showcase your new skills

Pro Logo

How you'll master it

Stress-test your knowledge with quizzes that help commit syntax to memory

Pro Logo