How do you extract associated values using `if case let` or `guard case let`?

iOS interview question for Intermediate practice.

Answer

if case let and guard case let allow you to check if an enum or optional matches a specific case and simultaneously bind its associated value(s) to local constants (let) or variables (var). if case let: Executes a block conditionally if the pattern matches. Bound values are only available inside the if block. swift enum NetworkResult { case success(Data) case failure(Error) } let result: NetworkResult = .success(Data([0, 1])) if case .success(let data) = result { // 'data' is bound to the associated Data value here print("Success with \(data.count) bytes") } else { print("Not success") } // Output: Success with 2 bytes guard case let: Ensures the pattern matches to continue execution in the current scope; otherwise exits via the else block. Bound values are available after the guard statement for the rest of the scope. swift func process(result: NetworkResult) { guard case .success(let data) = result else { print("Handling failure...") return // Must exit scope } // 'data' is available here onwards print("Processing success data: \(data.count) bytes") } process(result: .success(Data([1,2,3]))) // Output: Processing success data: 3 bytes process(result: .failure(NSError())) // Output: Handling failure... Syntax Notes: Use let to bind as constants, var to bind as variables. For optionals, you can use if case .some(let value) = opt or the shorthand if case let value? = opt.

Explanation

You can use within the pattern to ignore specific associated values you don't need to bind.

Related Questions