Swift:过滤字典 [英] Swift: filter dictionary

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

问题描述

我正在尝试在swift中过滤字典:

i am trying to filter a dictionary in swift:

var data: [String: String] = [:]
data = data.filter { $0.1 == "Test" }

上面的过滤器代码编译在swift 2下但产生以下错误:

the filter code above compiles under swift 2 but yields the following error:

Cannot assign a value of type '[(String, String)]' to a value of type '[String : String]'

这是swift编译器中的错误还是这个不是在swift中过滤字典的正确方法吗?

is this a bug in the swift compiler or is this not the right way to filter dictionaries in swift?

提前非常感谢!

推荐答案

这已在Swift 4中修复

let data = ["a": 0, "b": 42]
let filtered = data.filter { $0.value > 10 }
print(filtered) // ["b": 42]

在Swift中4,过滤的字典返回字典。

In Swift 4, a filtered dictionary returns a dictionary.

Swift 2和3的原始答案

问题是数据是一个字典,但过滤器的结果是一个数组,因此错误消息表明您无法将后者的结果分配给前者。

The problem is that data is a dictionary but the result of filter is an array, so the error message says that you can't assign the result of the latter to the former.

您可以创建一个新变量/结果数组的常量:

You could just create a new variable/constant for your resulting array:

let data: [String: String] = [:]
let filtered = data.filter { $0.1 == "Test" }

这里已过滤是一个元组数组: [(String,String)]

Here filtered is an array of tuples: [(String, String)].

过滤后,你如果这是你需要的,可以重新创建一个新词典:

Once filtered, you can recreate a new dictionary if this is what you need:

var newData = [String:String]()
for result in filtered {
    newData[result.0] = result.1
}

如果您决定不使用过滤器,您可以改变原始字典或其副本:

If you decide not to use filter you could mutate your original dictionary or a copy of it:

var data = ["a":"Test", "b":"nope"]
for (key, value) in data {
    if value != "Test" {
        data.removeValueForKey(key)
    }
}
print(data) // ["a": "Test"]

注意:在Swift 3中, removeValueForKey 已重命名 removeValue(forKey :) ,因此在此示例中它变为 data.removeValue(forKey:key)

Note: in Swift 3, removeValueForKey has been renamed removeValue(forKey:), so in this example it becomes data.removeValue(forKey: key).

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

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