Reputation: 41510
What's the underlying type for Tuple in Swift? I see one mention of Tuple in the Swift module but I can't any of the following:
var x: Tuple
var y: Optional<Tuple>
Is Tuple a compiler magic or an actual type in Swift?
Upvotes: 2
Views: 1693
Reputation: 108169
Declaring
let x: Tuple
doesn't make sense for two reasons:
It's pretty much as declaring
let x: Array
which is forbidden as well (the parametric type is missing)
The difference here is also that Tuple
is not a type per se. A tuple type is defined by both the types of the elements it holds and their number.
So a Tuple
type doesn't make sense, rather you will have several types Tuple2
, Tuple3
and so on. Each TupleX
has have X
type parameters, which will define the concrete type once provided.
In swift the compiler creates this types for you (I have no references for that, but it's the only reasonable assumption I can make), probably up to a finite number (which I still haven't found). The naming of this types doesn't look to be explicit, so you won't find a Tuple2
, but instead you'll have a ($T1, $T2)
type.
To sum it up, declaring a Tuple
parameter is meaningless for several reasons, but you can surely have something like
var x: (Int, String)
or
var y: Optional<(Int, String)>
and so on.
To further clarify my point, here's why Tuple2
and Tuple3
need to be two different types:
class Tuple2<T1,T2> {
init (_ e1: T1, _ e2: T2) {}
}
class Tuple3<T1,T2,T3> {
init (_ e1: T1, _ e2: T2, _ e3: T3) {}
}
Tuple2(1, "string")
Tuple3(1, "string", ["an", "array"])
This is probably similar to what the compiler generates, and you can easily see that each TupleX
takes a different number of type parameters, hence we need to define a type for each X.
Upvotes: 8
Reputation: 14851
This is just an educated guess, but what happens is probably the compiler treating tuples as instances of generic tuple classes (or structs). That is how Scala handles tuples.
Upvotes: 0
Reputation: 7501
I think it's like Anonymous Types in .net
For example, in C# you can do the following
var v = new { Amount = 108, Message = "Hello" }
just like in a Swift Tuple.
Therefore, I think it's much likely a compiler magic.
Upvotes: 0
Reputation: 3394
According to Apple's Swift book: Tuples group multiple values into a single compound value. The values within a tuple can be of any type and do not have to be of the same type as each other.
Upvotes: 0