Make a dictionary value non-optional as extension

被刻印的时光 ゝ 提交于 2019-12-06 16:04:15

Your method produces a dictionary of the same type [Key: Value] with Value being some optional type. What you probably want is to produce a dictionary of type [Key: Value.Wrapped]:

extension Dictionary where Value: OptionalType {

    func jsonSanitize() -> [Key: Value.Wrapped] {
        var newDict: [Key: Value.Wrapped] = [:]
        for (key, value) in self {
            if let v = value.asOptional {
                newDict.updateValue(v, forKey: key)
            }
        }
        return newDict
    }
}

Example:

let dict: [String: Int?] = [
    "foo": 1234,
    "bar": nil
]
var dict2 = dict.jsonSanitize()
print(dict2) // ["foo": 1234]

Note also that of Swift 3.0.1/Xcode 8.1 beta, optionals are bridged to NSNull instances automatically, see

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!