Search code examples
scalaswiftpattern-matchingtuplesdecompiling

How is named values for Tuple implemented in swift?


In swift, we can use tuple like this in the repl:

 34> let person:(name:String,age:Int)=("Hello",23)
person: (name: String, age: Int) = {
  name = "Hello"
  age = 23
}
 35> person.name
$R13: String = "Hello"
 36> person.age
$R14: Int = 23

I have not explicitly defined a type for person, and a Tuple of String and Int only have getters for 0 and 1.

Then how does the compiler know that person.name and person.age are legal invocations and person.something is not?

I ask this question because I always wanted the similar thing for Scala, but in Scala you can only do it like this:

scala> val person=("Hello",23)
person: (String, Int) = (Hello,23)

scala> val (name,age)=person
name: String = Hello
age: Int = 23

I either have to use pattern match explicitly or I have to use the _1 and _2 methods.

It seems like there is no decompiler that I can utilise to get the answer by myself, so I hope someone with the knowledge could help.


Solution

  • That is a tuple. In Swift, a tuple without named parametes will allow access via .0, .1, etc. If you name the parameters, then it just looks them up by name, as if it labeled each parameter. Because you did it at declaration, that tuple's elements have names, so you can call them by name. That is also why you cannot call a parameter that has not been named, such as .something. When you say you "haven't defined a type for person", you actually have; it's a tuple, defined as (String, Int).