- Tuples as Structs
- From Tuples to Structs
- Tuple Limitations
- Tuple Types
- Assigning Tuples
- Passing Tuples as Arguments
- Wrap-Up
From Tuples to Structs
You cannot easily convert a struct to a tuple, but you can (sort of) convert a tuple to a struct:
let labeledTuple = (a:1, b:"Hello", c:2.2) let mystruct = MyStruct(labeledTuple)
This example compiles and runs, but you're not actually creating a struct from the tuple. Instead, you're using the tuple as arguments to the struct's initializer. Tuples can be passed to nearly any argument list, for use as initializers, functions, methods, closures, and so forth.
Because of the way structs create default initializers, you can't build this struct with an unlabeled tuple, such as (1, "Hello", 2.2). You must first add an initializer that doesn't require labels. The following example creates that second initializer:
struct MyStruct { var a: Int var b: String var c: Double init (a: Int, b: String, c: Double) { self.a = a; self.b = b; self.c = c } init (_ a : Int, _ b : String, _ c : Double) { self.init(a:a, b:b, c:c) } } let labeledTuple = (a:1, b:"Hello", c:2.2) let mystruct = MyStruct(labeledTuple) let unlabeledTuple = (1, "Hello", 2.2) let mystruct2 = MyStruct(unlabeledTuple)
After you add initializers that match both labeled and unlabeled elements, you can construct structs from either kind of tuple.