Swift:将一组字典拼合成一本字典 [英] Swift: Flatten an array of dictionaries to one dictionary

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

问题描述

在Swift中,我试图将一组字典拼合成一个字典 即

In Swift, I am trying to flatten an array of dictionaries into one dictionary i.e

let arrayOfDictionaries = [["key1": "value1"], ["key2": "value2"], ["key3": "value3", "key4": "value4"]]


//the end result will be:   
 flattenedArray = ["key1": "value1", "key2": "value2", "key3": "value3", "key4": "value4"]

我尝试使用平面图,但是返回结果的类型是[(String, AnyObject)]而不是[String, Object]

I have tried using flatmap, but the type of the returned result is [(String, AnyObject)] and not [String, Object] ie

let flattenedArray = arrayOfDictionaries.flatMap { $0 }
// type is [(String, AnyObject)]

所以我有2个问题:

  • 为什么返回类型[[String,AnyObject)]?括号是什么意思?

  • Why is type [(String, AnyObject)] returned? And what do the brackets mean?

我如何获得理想的结果?

How do I achieve the desired result?

我更喜欢将功能性方法与Swift的map/flatmap/reduce等结合使用,而不是使用for

I would prefer to use a functional approach with Swift's map/flatmap/reduce etc. instead of a for-loop

推荐答案

方括号是什么意思?

what do the brackets mean?

这与逗号(而不是冒号)一起提供了第一个线索:方括号表示您获得了一个元组数组.由于您要查找的是字典,而不是数组,因此这告诉您需要将元组(键-值对)序列转换为单个字典.

This, along with a comma instead of a colon, should provide the first clue: brackets mean that you get an array of tuples. Since you are looking for a dictionary, not an array, this tells you that you need to convert the sequence of tuples (key-value pairs) to a single dictionary.

我如何获得理想的结果?

How do I achieve the desired result?

一种方法是使用reduce,例如:

One way to do it would be using reduce, like this:

let flattenedDictionary = arrayOfDictionaries
    .flatMap { $0 }
    .reduce([String:String]()) { (var dict, tuple) in
        dict.updateValue(tuple.1, forKey: tuple.0)
        return dict
    }

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

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