使字典值成为非可选的扩展

Make a dictionary value non-optional as extension

下面的 playground 概述了我的问题。该扩展将从我的字典中删除 nil 值,但将其他值保留为 Optional(Value)。我需要的是一个没有 nil 值并使可选值类型为非可选的字典。

例如:我有一本 [String:Int?] 的字典。我希望那个字典上调用的 jsonSantize() 到 return a [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)

您的方法生成相同类型的字典[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 个实例,参见