如何从元组数组创建字典? [英] How do I create dictionary from array of tuples?

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

问题描述

比方说,我有一些可以识别的对象,我想从中创建字典.我可以像这样轻松地从数组中获取元组:

Let’s say I have array of objects that can be identified and I want to create dictionary from it. I can easily get tuples from my array like so:

let tuples = myArray.map { return ($0.id, $0) }

但是我看不到字典的初始值设定项接受元组数组.我想念什么吗?我是否为此功能创建了字典扩展名(实际上并不难,但我认为默认情况下会提供),或者有更简单的方法做到这一点?

But I can’t see initializer for dictionary to take array of tuples. Am I missing something? Do I have create extension for dictionary for this functionality (in fact it’s not hard but I thought it would be supplied by default) or there is easier way to do that?

有扩展代码

extension Dictionary
{
    public init (_ arrayOfTuples : Array<(Key, Value)>)
    {
        self.init(minimumCapacity: arrayOfTuples.count)

        for tuple in arrayOfTuples
        {
            self[tuple.0] = tuple.1
        }
    }
}

推荐答案

Swift 4

如果您的元组是(Hashable,String),则可以使用:

If your tuples is (Hashable, String) you can use:

let array = [("key1", "value1"), ("key2", "value2"), ("key3", "value3")]
let dictionary = array.reduce(into: [:]) { $0[$1.0] = $1.1 }
print(dictionary) // ["key1": "value1", "key2": "value2", "key3": "value3"]

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

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