Search code examples
swiftstructdestructuring

Value-binding pattern with Swift structs


As the Programming Swift book describes, tuples can be destructured either in the assignment or by value-binding in a switch

let point = (3, 2)
switch point {
case let (x, y):
    print("The point is at (\(x), \(y)).")
}
let (a, b) = point
print("The point is at (\(a), \(b)).")

I can't find any mention of how to do the equivalent for structs. For example:

struct S {
    let a, b: Int
}
let s = S(a: 1, b: 2)

// This doesn't work:
// let (sa, sb): s
// 
// Outputs: error: expression type 'S' is ambiguous without more context
// let (sa, sb) = s
//                ^

Solution

  • This doesn't exist as such in the language.

    One option is a helper computed property:

    struct S {
        let i: Int
        let b: Bool
    }
    
    extension S {
        var destructured: (Int, Bool) {
            return (self.i, self.b)
        }
    }
    
    let s = S(i: 10, b: false)
    let (i, b) = s.destructured
    

    Of course, you have to manually keep that in sync. Possibly Sourcery could assist with that.