I'm working on a Dictionary extension that seems to be doing some odd things. The below playground replicates the issue I'm seeing. If you start a new playground in XCode, you should be able to just paste this in and see the output and the issue. When checking the self[key] != nil
it comes back true for Optional(nil)
, but seemingly should not. So, when it checks "things" I'd think the check would fail, thus skipping adding it to newDict, but it does not.
//: Playground - noun: a place where people can play
import UIKit
import Foundation
extension Dictionary {
//Sanitizes the current dictionary for json serialization
//Removes nil values entirely. Makes optionals non-optional
func jsonSanitize() -> Dictionary<Key,Value> {
var newDict:[Key:Value] = [:]
for key in self.keys {
print(self[key])
print(self[key] != nil)
if self[key] != nil {
print("Adding it")
newDict.updateValue(self[key]!, forKey: key)
}
}
return newDict
}
}
var youGood = false
var dict:[String:Any] = [
"stuff":"THINGIES",
"things":
youGood ?
"WOHOO!" :
nil as String?
]
var dict2 = dict.jsonSanitize()