Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
struct Order { var id: Int var customer: Customer? } struct Customer { var name: String var address: Address? func loyaltyPoints() -> Int? { nil } // might not be enrolled } struct Address { var city: String var country: String } let order = Order(id: 1, customer: Customer(name: "Alice", address: Address(city: "London", country: "UK"))) // Optional chaining let city = order.customer?.address?.city // Optional("London") let points = order.customer?.loyaltyPoints() // Optional(Optional(nil)) without flatMap // Optional.map let upperCity = city.map { $0.uppercased() } // Optional("LONDON") // Optional.flatMap - flattens Optional<Optional<T>> let safePoints = order.customer.flatMap { $0.loyaltyPoints() } // nil // compactMap on array let strings = ["1", "abc", "3", "xyz", "5"] let numbers = strings.compactMap(Int.init) // [1, 3, 5] // Chaining with subscript let scores: [String: [Int]] = ["Alice": [90, 85, 92]] let firstScore = scores["Alice"]?.first // Optional(90)
Result
Open