In Swift, an Optional is a way to say “this value might be there, or it might be missing.” We use ? to show that a value is optional, like: var name: String? But what is really happening behind the scenes? What an Optional Really Is Inside Swift, an Optional is just a simple enum with two cases: enum Optional<Wrapped> { case none // no value case some(Wrapped) // has a value } That’s all an Optional is! So when you write: var age: Int? Swift actually thinks: var age: Optional<Int> The ? is only a shortcut for us. Why Optionals Feel Special Even though Optionals are simple, Swift gives them extra features: if let and guard let value ?? defaultValue value! for force unwrap a?.b?.c for optional chaining These special features work only with Swift’s built-in Optional. How Swift Stores Optionals Swift stores Optionals in a smart way: Many Optionals take no extra memory compared to the normal value. Swift uses unused bits or adds a small...
Blog by Jeevan
Mobile App Developer | Technopreneur