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

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

问题描述

我有一个大型数组,需要通过一个键(查找)来访问它,所以我需要创建Dictionary。有没有一个内置的函数在Swift 3.0中这样做,还是我需要自己写?

首先,我将需要它为一个类与键字符串后来也许我可以为通用目的(所有类型的数据和键)编写一个模板版本。 解决方案

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

$ p $ {
public func toDictionary< Key:Hashable> (使用selectKey:(Element) - > Key) - > [Key:Element] {
var dict = [Key:Element]()
for self {
dict [selectKey(element)] = element
}





$ b现在你可以这样做:

  struct Person {
var name:String
var surname:String
var identifier:String $ b (姓名:John,姓:Doe,标识符:JOD),
个人(姓名:Jane,姓: (dict)//结果:[JAD:Person(name) :Jane,姓:Doe,标识符:JAD),JOD:人(姓名:John,姓:Doe,标识符:JOD)]




如果你希望你的代码更一般,你甚至可以添加这个序列而不是 Array

 扩展序列{
pub lic func toDictionary< Key:Hashable>(with selectKey:(Iterator.Element) - > Key) - > [Key:Iterator.Element] {
var dict:[Key:Iterator.Element] = [:]
for self {
dict [selectKey(element)] = element

return dict


code


,这会导致序列迭代,在某些情况下可能有副作用。


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?

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).

解决方案

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

You can now do:

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")]


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

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

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

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