Skip to content

Instantly share code, notes, and snippets.

@erica
Last active June 12, 2016 08:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save erica/aab7c799f452e6043d87f90723ea137b to your computer and use it in GitHub Desktop.
Save erica/aab7c799f452e6043d87f90723ea137b to your computer and use it in GitHub Desktop.

Adding Conditional Binding with Tuples

Introduction

This proposal introduces tuple-based if-let assignments to the Swift programming language.

Swift Evolution Discussion: [Accepted with Revision] SE-0099 Restructuring Condition Clauses

Motivation

SE-0099 removed cascaded if-let statements that allowed groups of conditional binding to omit the let keyword. This proposal re-introduces the convenience of multiple simultaneous conditional assignments.

Instead of using cascades like:

guard let a = opt1, b = opt2, c = opt3 else { ... leave scope ... }

You must now use the let keyword for each binding:

guard let a = opt1, let b = opt2, let c = opt3 else { ... leave scope ... }

Given that you can still use tuples with case, e.g.

guard case (.none, .none, .none) = (foo(), bar(), blort()) else { ... }
guard case (.Some(let a), .Some(let b), .Some(let c)) = (foo(), bar(), blort()) else { ... }

It seems only fair that if-let, guard-let, and while let should permit an analogous construct without using the extra verbiage required for case:

guard let (x, y, z) = (foo(), bar(), blort()) else { ... } // illegal

Unfortunately, they do not:

// error: initializer for conditional binding must have 
// Optional type, not '(Int?, Int?, Int?)' (aka 
// '(Optional<Int>, Optional<Int>, Optional<Int>)')

Detailed Design

This proposal extends Swift's public facing API to support conditional tuple bindings with simple let patterns, just as it does for case:

optional_binding_condition : 'let' pattern initializer | 'var' pattern initializer

Impact on Existing Code

This proposal is additive

Alternatives Considered

Not accepting this proposal

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment