Swift 3:数组到字典? [英] Swift 3: Array to Dictionary?

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

问题描述

我有一个大数组,需要通过键(查找)访问它,所以我需要创建字典.Swift 3.0 中是否有内置函数可以这样做,还是需要我自己编写?

I have a large array and need to access it by a key (a lookup) so I need to create Dictionary. Is there a built in function in Swift 3.0 to do so, or do I need to write it myself?

首先,我将需要它用于带有键String"的类,然后也许我将能够为通用(所有类型的数据和键)编写模板版本.

First I will need it for a class with key "String" and later on maybe I will be able to write a template version for general purpose (all types of data and key).

2019 年注意事项.现在只是内置于 Swift 5uniqueKeysWithValues 和类似的调用.

Note for 2019. This is now simply built-in to Swift 5, uniqueKeysWithValues and similar calls.

推荐答案

我想你正在寻找这样的东西:

I think you're looking for something like this:

extension Array {
    public func toDictionary<Key: Hashable>(with selectKey: (Element) -> Key) -> [Key:Element] {
        var dict = [Key:Element]()
        for element in self {
            dict[selectKey(element)] = element
        }
        return dict
    }
}

您现在可以:

struct Person {
    var name: String
    var surname: String
    var identifier: String
}

let arr = [Person(name: "John", surname: "Doe", identifier: "JOD"),
           Person(name: "Jane", surname: "Doe", identifier: "JAD")]
let dict = arr.toDictionary { $0.identifier }

print(dict) // Result: ["JAD": Person(name: "Jane", surname: "Doe", identifier: "JAD"), "JOD": Person(name: "John", surname: "Doe", identifier: "JOD")]

<小时>

如果你想让你的代码更通用,你甚至可以在 Sequence 而不是 Array 上添加这个扩展:


If you'd like your code to be more general, you could even add this extension on Sequence instead of Array:

extension Sequence {
    public func toDictionary<Key: Hashable>(with selectKey: (Iterator.Element) -> Key) -> [Key:Iterator.Element] {
        var dict: [Key:Iterator.Element] = [:]
        for element in self {
            dict[selectKey(element)] = element
        }
        return dict
    }
}

请注意,这会导致 Sequence 被迭代并且在某些情况下可能会产生副作用.

Do note, that this causes the Sequence to be iterated over and could have side effects in some cases.

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

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