In Swift, is there a way to determine through code if a variable passed in is reference type or value type?
For example, is tuple a value type or reference type?
afaik, to pass by reference you need to add the inout
keyword in front of the parameter definition. all other parameters are constants unless prefixed with the var
keyword
“Function parameters are constants by default. Trying to change the value of a function parameter from within the body of that function results in a compile-time error. This means that you can’t change the value of a parameter by mistake.”
and...
“Variable parameters, as described above, can only be changed within the function itself. If you want a function to modify a parameter’s value, and you want those changes to persist after the function call has ended, define that parameter as an in-out parameter instead.”
Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/us/jEUH0.l
Everything is a value type except for:
An instance of a class
A function
An array (which works in an odd way; it is passed by reference but can become unbound from its other avatars if it is mutable and the number of items is changed)
The simple code way to test is just to assign to two different var
names, change one, and see if they are still equal. For example:
var tuple1 = (1,2)
var tuple2 = tuple1
tuple1.1 = 3
println(tuple1)
println(tuple2)
They are different, proving that a tuple is passed by value. But:
var arr1 = [1,2]
var arr2 = arr1
arr1[1] = 3
println(arr1)
println(arr2)
They are the same, proving that an array is passed by reference.
EDIT:
But in beta 3 of Swift, this unusual behavior of Array is withdrawn, and only class instances and functions are passed by reference. Everything else is passed by value now.