Swift provides us with a shortcut when using optionals: if you want to access something like
b is optional, you can write a question mark after it to enable optional chaining:
When that code is run, Swift will check whether
b has a value, and if it’s
nil the rest of the line will be ignored – Swift will return
nil immediately. But if it has a value, it will be unwrapped and execution will continue.
To try this out, here’s an array of names:
let names = ["John", "Paul", "George", "Ringo"]
We’re going to use the
first property of that array, which will return the first name if there is one or
nil if the array is empty. We can then call
uppercased() on the result to make it an uppercase string:
let beatle = names.first?.uppercased()
That question mark is optional chaining – if
nil then Swift won’t try to uppercase it, and will set
SPONSORED Instabug helps you identify and resolve severe crashes quickly. You can retrace in-app events and know exactly which line of code caused the crash along with environment details, network logs, repro steps, and the session profiler. Ask more questions or keep users up-to-date with in-app replies straight from your dashboard. Instabug takes data privacy seriously, so no one sees your data but you! See more detailed features comparison and try Instabug's crash reporting SDK for free.