-1

By trial&error I found some facts about tuples and mutability in Swift, but would like to learn about actual rules. Consider such code:

class T
{
    var f : String = "hello"
}

let a = T();
let b = (f : "hello", "");
a.f = "world";
b.f = "world";
println(a.f)
println(b.f)

a behaves like fixed reference (you can change any member you like of the object, just not the main reference). So it is like readonly in C#.

But b behaves more like constant value -- the above code does not compile. One could say that let (or var) is applied to all the members of the tuple.

But it is guessing from my part -- so back to my question. What are the rules for tuples and their mutability?

greenoldman
  • 16,895
  • 26
  • 119
  • 185
  • possible duplicate of [Is Swift Pass By Value or Pass By Reference](http://stackoverflow.com/questions/27364117/is-swift-pass-by-value-or-pass-by-reference) – matt Feb 02 '15 at 16:51
  • @matt, to make a real answer to my question I would have to know if tuple is defined as value type (`struct`) or reference one (`class`), but this info I also cannot find. – greenoldman Feb 02 '15 at 17:02
  • 1
    @greenoldman as stated in the Swift guide, tuples are compound data types. Therefore, defining it as `let` makes it and its "members" immutable. – Sebastian Feb 02 '15 at 17:30
  • 1
    But the other question's answer answers that. Everything except class instance or function is a value type. Tuple is not class instance or function. Can you do the logic? – matt Feb 02 '15 at 17:33
  • @matt, and how do I know if `tuple` is not defined as `class` internally? – greenoldman Feb 02 '15 at 17:49
  • @SebastianDressler, thank you. Could you post is as regular answer so I could accept it? Now, knowing what to look for I found how Swift differentiates types -- to named and compound ones. – greenoldman Feb 02 '15 at 17:52
  • @greenoldman It's just like how you know that struct is not defined as class internally, or how you know that tiger is not defined as hollyhock internally. :) – matt Feb 02 '15 at 18:09

1 Answers1

1

As stated in The Swift Programming Language: The Basics, tuples are compound types in Swift. Therefore, if one creates a constant variable with let which has a tuple as type, all values in the tuple become constant too.

Sebastian
  • 8,046
  • 2
  • 34
  • 58