Reputation: 39
I've been trying to swap 2 objects without using a temp value, which be done like so:
var a = "Hello, "
var b = "world!"
(a,b) = (b,a)
a // "world!"
b // "Hello, "
Does anyone know how the language is doing this, is the second tuple (b,a) stored in memory to allow the first one to reassign itself, or does it do it all by switching references?
Thanks in advance
Upvotes: 2
Views: 293
Reputation: 45210
This kind of "switching" does the following:
Replaces the pointers for class types
var classA = NSString(string: "foo")
var classB = NSString(string: "bar")
NSLog("%p %p", classA, classB) // 0x7fecd351def0 0x7fecd341cc30
(classA, classB) = (classB, classA)
NSLog("%p %p", classA, classB) // 0x7fecd341cc30 0x7fecd351def0
Creates new values (copies) for value types
var valueA = "baz"
var valueB = "qux"
NSLog("%p %p", valueA, valueB) // 0x7fecd34201b0 0x7fecd34211e0
(valueA, valueB) = (valueB, valueA)
NSLog("%p %p", valueA, valueB) // 0x7fecd351c880 0x7fecd351de90
Upvotes: 1