Davor Cubranic
Davor Cubranic

Reputation: 1120

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
//                ^

Upvotes: 5

Views: 1809

Answers (2)

jscs
jscs

Reputation: 64002

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.

Upvotes: 4

Daniel
Daniel

Reputation: 3597

Structs cannot be destructured in Swift.

Your tuple, point = (3, 2), is of type (Int, Int), which is part of why you are able to destructure it.

The type of your struct, S, is just S. Its variables, a and b, are not included in its type in the same literal way as they are for a tuple. A struct is simply a completely different kind of object, and this behavior does not exist for it.

Upvotes: 3

Related Questions