Swift Language Optionals

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Introduction

“ An optional value either contains a value or contains nil to indicate that a value is missing”

Excerpt From: Apple Inc. “The Swift Programming Language (Swift 3.1 Edition).” iBooks. https://itun.es/us/k5SW7.l

Basic optional use cases include: for a constant (let), use of an optional within a loop (if-let), safely unwrapping an optional value within a method (guard-let), and as part of switch loops (case-let), defaulting to a value if nil, using the coalesce operator (??)

Syntax

  • var optionalName: optionalType? // declare an optional type, defaults to nil
  • var optionalName: optionalType? = value // declare an optional with a value
  • var optionalName: optionalType! // declare an implicitly unwrapped optional
  • optional! // force unwrap an optional

Remarks

For more information about optionals, see The Swift Programming Language.



Got any Swift Language Question?