Properties2
| Type | Concept |
| Note created | Feb 17, 2025 |
In Swift, there are several ways to work with optional values, that is, values that be nil. A type is nullable if it suffixed with an interrogation, for example, let example: String?.
To unpack an optional value, we can use if let and guard let clauses, which assign the value to a constant.
if letwill provide the constant within a given scope to manipulate it.guard letwill run the code provided if value isnil(for an early return).
Another way to deal with these kind of values is coalescing them, that is, providing a value to be used in case the given variable is null.
let unpacked = optional ?? 42It is also important to know about chained optionals, where we call functions over optional types in case they are available. For example, this code:
var book: Book? = nil
let author = book?.author?.first?.uppercased() ?? "A"Reads as “if there is a book, and it has an author, get me the first letter uppercased; otherwise return A”.