将字典值设为非可选扩展名 [英] Make a dictionary value non-optional as extension

查看:76
本文介绍了将字典值设为非可选扩展名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The below playground outlines my issue. The extension will remove nil values from my dictionary, but leave the other values as Optional(Value). What I need is a dictionary that has no nil values and make the optional value type non-optional.

例如:我有一个[String:Int?]字典.我希望在该词典上调用的jsonSantize()返回[String:Int].

Ex: I have a dictionary of [String:Int?]. I want the jsonSantize() of that called on that dictionary to 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作为新的字典类型

UPDATE: Suggestion made to use Value.Wrapped as new dictionary type

//: 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]类型的字典:

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
    }
}

示例:

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实例,请参见

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

这篇关于将字典值设为非可选扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆