Skip to content

Instantly share code, notes, and snippets.

@raheelahmad
Last active June 20, 2016 17:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raheelahmad/26472d623e2af3167fe86c13f3dc2ff5 to your computer and use it in GitHub Desktop.
Save raheelahmad/26472d623e2af3167fe86c13f3dc2ff5 to your computer and use it in GitHub Desktop.
Swift 2.2 bug with optimization on
// 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)
}
@raheelahmad
Copy link
Author

raheelahmad commented Jun 16, 2016

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment