A concise, runnable playground demonstrating how to force unwrap Swift optionals.
Force unwrapping is how you access the value stored inside a Swift optional by adding a ! after it, telling the compiler you are certain the optional is not nil. If the optional turns out to be nil at runtime, the program crashes β which makes force unwrapping powerful but risky.
This is a short, runnable learning example (a Swift Playground) that shows a few common force-unwrapping situations so you can see the concept in action.
- Force unwrapping the result of a failable initializer (
Double("3.14")!). - Force unwrapping an optional array parameter passed into a function.
- Force unwrapping an optional stored property on a
struct. - Printing the unwrapped values to observe the results in the playground console.
git clone https://github.com/ahmetbostanciklioglu/ForceUnwrapping.git
cd ForceUnwrappingUnzip ForceUnwrapping.playground.zip, open ForceUnwrapping.playground in Xcode, and run it (Playgrounds execute automatically, or press Shift + Command + Return to re-run) to see the output in the console.
- macOS with Xcode 12 or later
- Swift 5
Ahmet BostancΔ±klΔ±oΔlu β @ahmetbostanciklioglu Β· ahmetbostancikli@gmail.com
β If this helped you, consider giving the repo a star!