首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >flatMap --斯威夫特词典词典

flatMap --斯威夫特词典词典
EN

Stack Overflow用户
提问于 2016-08-15 17:48:31
回答 2查看 2.2K关注 0票数 1

我有一个NSEnumerator,它包含嵌套的键值对象,如下所示:

代码语言:javascript
复制
 [ "posts" :
    ["randonRootKey1" :
        ["randomChildKey1" : [:] ]
    ], 
    ["randonRootKey2" :
        ["randomChildKey2" : [:] ],
        ["randomChildKey3" : [:] ],
    ]  
]

- posts
-- user1
--- posts
----post
-- user2
-- posts
--- post 

我想在一个数组中提取所有用户的所有帖子.最后一个孩子和所有的父母都是字典

我想flatMap它是:

代码语言:javascript
复制
[
        ["randomChildKey1" : [:] ],
        ["randomChildKey2" : [:] ],
        ["randomChildKey3" : [:] ]
]

注意,我已经提取了每个根字典的对象。

我试过:

代码语言:javascript
复制
let sub = snapshot.children.flatMap({$0}) 

但似乎不起作用

EN

回答 2

Stack Overflow用户

发布于 2016-08-15 18:33:24

代码语言:javascript
复制
 let input: [String: [String: [String: Any]]] = ["posts":
    [
        "randonRootKey1": [
            "randomChildKey1": [:],
        ],
        "randonRootKey2": [
            "randomChildKey2": [:],
            "randomChildKey3": [:],
        ]
    ]
]

var output = [String: Any]()

for dictionary in input["posts"]!.values {
    for (key, value) in dictionary {
        output[key] = value
    }
}

print(output)

["randomChildKey3":"randomChildKey2":"randomChildKey1":]

票数 1
EN

Stack Overflow用户

发布于 2016-08-15 19:15:06

假设输入为此格式

代码语言:javascript
复制
let input: [String: [String: [String: Any]]] = ["posts":
    [
        "randonRootKey1": [
            "randomChildKey1": [:],
        ],
        "randonRootKey2": [
            "randomChildKey2": [:],
            "randomChildKey3": [:],
        ]
    ]
]

用这个

代码语言:javascript
复制
let output = input.flatMap{$0.1}.flatMap{$0.1}

您将获得所需的输出

[("randomChildKey1",),("randomChildKey2",),("randomChildKey3“)]

如果要将元组转换为字典,请使用reduce

代码语言:javascript
复制
let output = input.flatMap{$0.1}.flatMap{$0.1}.reduce([String: Any]())
{
    (var dict, tuple) in
    dict.append([tuple.0: tuple.1])
    return dict
}

["randomChildKey1":{},"randomChildKey2":{},"randomChildKey3":{}]

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38960210

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档