Optionals
Learn how to use optionals to handle data that might be nil.
StartKey Concepts
Review core concepts you need to learn to master this subject
Optional Types
Force Unwrapping Optionals
Optional Binding
Multiple Optional Bindings
Guard Statements
Nil-Coalescing Operator
Optionals and Functions
Optional Types
Optional Types
var email: String? = nil
email = "[email protected]"
Optionals types are declared with a ?
after the type name. Optionals either contain a value or nil which represents the absence of a value.
Optionals
Lesson 1 of 1
- 1Sometimes 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…
- 2Optional 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…
- 3Once 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 …
- 4In 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…
- 5if 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…
- 6Guard 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…
- 7The 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…
- 8It’s common in Swift to chain properties and method calls on a variable: let instrument = “piano” let firstUppercasedCharacter = instrument.uppercased().first print(firstUppercasedCharacter) // pr…
- 9Because 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…
What you'll create
Portfolio projects that showcase your new skills
How you'll master it
Stress-test your knowledge with quizzes that help commit syntax to memory