Swift Dictionary is returning a different object for the same key

I'm in the process of switching over one of my projects from Obj-C to Swift, and I've ran into a problem when switching from NSDictionary/NSMutableArray to Dictionary/Array. Since I'm grabbing the value for "key" I assume that it would be returning the same Array it's pointing to as it does in Obj-C, but thats not the case. I wrote a small sample replicating the bug. a Tip in the right direction would be much appreciated. Thanks in advance

var test:[ [String:[String]] ]

init() {

test = [ [String:[String]] ]()

var first:[String] = _arrayForKey("key")
first.append("first")

var second:[String] = _arrayForKey("key")
second.append("second")

var third:[String] = _arrayForKey("key")
third.append("third")

var fourth:[String] = _arrayForKey("key")
fourth.append("fourth")

println(work)
}

private func _arrayForKey(key:String) -> [String] {

for dict in test {
    if dict.keys.first! == key {
        return dict[key]!
    }
}

test.append([key:[String]()])
var dict:[String:[String]] = test.last!

println("MAKING A NEW DICTIONARY \(test)")
return dict[key]!
}

When ran it logs out ["fourth"], what I'm looking for is ["first", "second", "third", "fourth"]

Answers


It's not a bug.

Unlike in Objective-C where NSArray and NSDictionary are reference types, Array and Dictionary in Swift are value types, for example

var array1 = [1, 2, 3]
var array2 = array1 // array is copied
array1[2] = 4
println(array1) // -> [1, 2, 4]
println(array2) // -> [1, 2, 3]

Need Your Help

spring boot + hibernate 5 + java 8 + ZonedDateTime = ImplicitNamingStrategy exception

postgresql spring-boot java-8 hibernate-5.x

I have an spring boot app that leverage the java 8 and have used hibernate 4 so far. I needed however to change part of my model to include the new ZonedDateTime class provided by java8 i.e. I need...

MagicalRecord/MagicalRecordDeprecationMacros.h file not found

magicalrecord magicalrecord-2.2 magicalrecord-2.1

I down load the Magical Record master. Drag the MagicalRecord folder to my project. Import CoreData.framework then build. Show the error "MagicalRecord/MagicalRecordDeprecationMacros.h file not fo...