Skip to content

Instantly share code, notes, and snippets.

This gist was prompted by a discussion on the iOhYes podcast about the Swift Language. Although Swift Dictionaries are Structs and therefore value types, when there are references inside, are they copied or referenced? The hosts didn't know, so I decided to experiment.
// Make a class for use on this playground
class Foo {
var Bar : String = ""
var Baz : Int = 0
}
// Make one object
var originalFoo = Foo()
originalFoo.Bar = "Lorem Ipsum"
originalFoo.Baz = 7
// Copy the reference to another variable
var referencedFoo = originalFoo
// Make another independent object
var anotherFoo = Foo()
anotherFoo.Bar = "We the people"
anotherFoo.Baz = 77
// Check our references to show how the comparisons work
println("Are originalFoo and referencedFoo the same object? \(originalFoo === referencedFoo)")
println("Are originalFoo and anotherFoo the same object? \(originalFoo === anotherFoo)")
println("Are referencedFoo and anotherFoo the same object? \(referencedFoo === anotherFoo)")
// Make a dictionary to hold our objects
var originalDict = ["KeyOne": originalFoo, "KeyTwo":anotherFoo]
// Copy the dictionary to another variable
var copiedDict = originalDict
// Are the dictionaries the same object?
// We can't check because dictionaries aren't objects at all, they are structs
// We get the error: // Type '[String: Foo]' does not conform to protocol 'AnyObject'
// Because Dictionary isn't a class and doesn't conform to AnyObject, so
// we can be certain these are different things in memory entirely
// copiedDict === originalDict
// Check the keys in each dictionary against each other
var keyOneResult = originalDict["KeyOne"] === copiedDict["KeyOne"]
var keyTwoResult = originalDict["KeyTwo"] === copiedDict["KeyTwo"]
var mixedKeyResult = originalDict["KeyOne"] === copiedDict["KeyTwo"]
// Print out the results
println("Are the values for first keys in the two dictionaries the same object? \(keyOneResult)")
println("Are the values for second keys in the two dictionaries the same object? \(keyTwoResult)")
println("Is the value of the first key in the original dictionary the same object as the value of the second key in the copied dictionary? \(mixedKeyResult)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment