下面的游乐场概述了我的问题。扩展名将从我的字典中删除nil值,但将其他值保留为Optional(Value)。我需要的是一个没有nil值的字典,并使可选的值类型非可选。
Ex:我有[String:Int?]
字典。我希望该字典上调用的jsonSantize()
返回[String:Int]
。
//: Playground - noun: a place where people can play
import UIKit
import Foundation
protocol OptionalType {
associatedtype Wrapped
var asOptional : Wrapped? { get }
}
extension Optional : OptionalType {
var asOptional : Wrapped? {
return self
}
}
extension Dictionary where Value : OptionalType{
//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, value) in self {
if value.asOptional != nil {
newDict.updateValue(self[key]!, forKey: key)
}
}
return newDict
}
}
var youGood = false
var stringMan:String? = youGood ?
"WOHOO!" :
nil
var dict:[String:Any?] = [
"stuff":"THINGIES",
"things": stringMan
]
var dict2 = dict.jsonSanitize()
print(dict2)
var test = (stringMan != nil)
更新:建议使用Value.Wrapped作为新词典类型
//: Playground - noun: a place where people can play
import UIKit
import Foundation
protocol OptionalType {
associatedtype Wrapped
var asOptional : Wrapped? { get }
}
extension Optional : OptionalType {
var asOptional : Wrapped? {
return self
}
}
extension Dictionary where Value : OptionalType{
//Sanitizes the current dictionary for json serialization
//Removes nil values entirely. Makes optionals non-optional
func jsonSanitize() -> Dictionary<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
}
}
var youGood = false
var stringMan:String? = youGood ?
"WOHOO!" :
nil
var dict:[String:Any?] = [
"stuff":"THINGIES",
"things": stringMan
]
var dict2:[String:Any] = dict.jsonSanitize()
print(dict2)
var test = (stringMan != nil)
答案 0 :(得分:2)
您的方法会生成相同类型的字典[Key: Value]
Value
是一些可选类型。你可能想要的是什么
生成[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
}
}
示例:
let dict: [String: Int?] = [
"foo": 1234,
"bar": nil
]
var dict2 = dict.jsonSanitize()
print(dict2) // ["foo": 1234]
还要注意 Swift 3.0.1 / Xcode 8.1 beta,选项
自动桥接到NSNull
实例,请参阅