我正在研究一个似乎在做一些奇怪事情的字典扩展。下面的游乐场复制了我所看到的问题。如果你在XCode中开始一个新的游乐场,你应该可以将其粘贴进去并查看输出和问题。检查self[key] != nil
时Optional(nil)
的回复是真的,但似乎不应该。因此,当它检查“事物”时,我认为检查会失败,因此跳过将其添加到newDict,但事实并非如此。
//: 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()