我正在开发一个似乎在做一些奇怪事情的字典扩展。下面的操场复制了我看到的问题。如果您在 XCode 中创建一个新的 Playground,您应该可以将其粘贴进去并查看输出和问题。检查时self[key] != nil
它返回 true 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()