Last active
June 20, 2016 17:13
-
-
Save raheelahmad/26472d623e2af3167fe86c13f3dc2ff5 to your computer and use it in GitHub Desktop.
Swift 2.2 bug with optimization on
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This shows a bug in Swift 2.2 (and 2.3) where `self` gets released in a recursive call | |
extension Dictionary { | |
mutating func append(_ other: [String: AnyObject]) { | |
// 2. After the call 1. below, `other` would have been dealloced in the recursive call :( | |
for (key, value) in other { | |
if let otherSubDict = value as? [String: AnyObject], | |
var selfSubDict = self[key] as? AnyObject as? [String: AnyObject] | |
{ | |
// 1. Make a recursive call | |
selfSubDict.append(otherSubDict) | |
self.updateValue(selfSubDict, forKey: key) | |
} else { | |
self.updateValue(value, forKey: key) | |
} | |
} | |
} | |
subscript (key: AnyObject) -> Value? { | |
if let key = key as? Key { | |
return self[key] | |
} | |
return nil | |
} | |
mutating func updateValue(_ value: AnyObject, forKey key: AnyObject) { | |
if let value = value as? Value, let key = key as? Key { | |
self.updateValue(value, forKey: key) | |
} | |
} | |
} | |
func testAppend() { | |
let key = "names" | |
var info = [ | |
key: | |
[ "first": "Raheel" ] | |
] | |
info.append([ | |
key: ["second": "Ahmad"] | |
] | |
) | |
print(info) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This shows a bug in Swift 2.2 (and 2.3) in Release build, with optimization on. The passed argument
other
gets released in a recursive call. Supposedly, has to do with ARC (Dictionary
uses ARC internally). Does not affect Swift 3.0