通用Swift字典扩展为nil过滤 [英] Generic Swift Dictionary Extension for nil filtering

查看:162
本文介绍了通用Swift字典扩展为nil过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找类型安全的此答案的通用版本。



这是我正在查找的方法签名:

 扩展词典其中值==可选< T> {
func filterNil() - > < Key,T>
}

有没有什么方法可以在Swift 3中表达这一点?



编辑

创建带有可选值的字典的动机是我需要类似这样的东西:

  struct User {
var mail:String?
var name:String?

func marshaled() - > [String:Any] {
return [
mail:mail,
name:name
] .filterNil()
}
}

我更喜欢字典文字来创建空字典并手动填充值。

解决方案

更新 Swift 4

  let filtered = dict.filter({$ 0.value!= nil})。mapValues({$ 0!})

这是目前正在讨论 if Dictionary 应该得到
a compactMapValues 方法,它结合了过滤器 mapValues






以前的答案:
您可以使用与

a>和创建扩展在Swift中过滤Array中的nils
定义所有可选项符合的协议:


  protocol OptionalType {
associatedtype Wrapped
func intoOptional() - >包裹?
}

扩展可选:OptionalType {
func intoOptional() - >包裹? {
return self
}
}

然后你的字典扩展名可以定义为:

 扩展词典其中Value:OptionalType {
func filterNil() - > [Key:Value.Wrapped] {
var result:[Key:Value.Wrapped] = [:]
for self(
如果let unwrappedValue = value.intoOptional (){
result [key] = unwrappedValue
}
}
返回结果
}
}

p>

示例:

  let dict = [mail :nil,name:John Doe] // Type是[String:String?] 
let filtered = dict.filterNil()// Type是[String:String]
print过滤)//输出:[name:John Doe]


I'm looking for a type safe, generic version of this answer.

This is the method signature I'm looking for:

extension Dictionary where Value == Optional<T> {
    func filterNil() -> <Key, T>
}

Is there any way to express this in Swift 3?

Edit:

My motivation for creating a Dictionary with optional values is that I need something like this:

struct User {
    var mail: String?
    var name: String?

    func marshaled() -> [String: Any] {
        return [
            "mail": mail,
            "name": name
        ].filterNil()
    }
}

I much prefer the dictionary literal to creating an empty dictionary and filling the values manually.

解决方案

Update: As of Swift 4, you can simply do

let filtered = dict.filter( { $0.value != nil }).mapValues( { $0! })

It is currently being discussed if Dictionary should get a compactMapValues method which combines filter and mapValues.


(Previous answer:) You can use the same "trick" as in How can I write a function that will unwrap a generic property in swift assuming it is an optional type? and Creating an extension to filter nils from an Array in Swift: define a protocol to which all optionals conform:

protocol OptionalType {
    associatedtype Wrapped
    func intoOptional() -> Wrapped?
}

extension Optional : OptionalType {
    func intoOptional() -> Wrapped? {
        return self
    }
}

Then your dictionary extension can be defined as:

extension Dictionary where Value: OptionalType {
    func filterNil() -> [Key: Value.Wrapped] {
        var result: [Key: Value.Wrapped] = [:]
        for (key, value) in self {
            if let unwrappedValue = value.intoOptional() {
                result[key] = unwrappedValue
            }
        }
        return result
    }
}

Example:

let dict = ["mail": nil, "name": "John Doe"] // Type is [String : String?]
let filtered = dict.filterNil() // Type is [String : String]
print(filtered) // Output: ["name": "John Doe"]

这篇关于通用Swift字典扩展为nil过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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