Level Up Coding

Coding tutorials and news. The developer homepage gitconnected.com && skilled.dev && levelup.dev

Follow publication

Swift under the hood: Optionals

Farhana Mustafa
Level Up Coding
Published in
3 min readMar 8, 2023

Photo by Markus Winkler on Unsplash

First things first — Enums with associated values

Revealing what an Optional really is

@frozen public enum Optional<Wrapped>: ExpressibleByNilLiteral {

/// The absence of a value.
///
/// In code, the absence of a value is typically written using the `nil`
/// literal rather than the explicit `.none` enumeration case.
case none

/// The presence of a value, stored as `Wrapped`.
case some(Wrapped)
}
var x: Int? = .none
var num1: Int? = nil
var num2: Optional<Int> = .none // Same implementation without the shorthand

var string1: String? = "Hello, World!"
string1 = .some("Hello, World!") // Same value as string1

Resources

No responses yet

Write a response