将对象数组映射到Swift中的Dictionary [英] Map array of objects to Dictionary in Swift

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

问题描述

我有一个 Person 的对象数组:

class Person {
   let name:String
   let position:Int
}

,数组是:

let myArray = [p1,p1,p3]

我想将 myArray 映射为的字典[position:name] 经典的解决方案是:

I want to map myArray to be a Dictionary of [position:name] the classic solution is:

var myDictionary =  [Int:String]()

for person in myArray {
    myDictionary[person.position] = person.name
}

Swift是否有任何优雅的方式使用功能方法 map flatMap ...或其他现代Swift风格

is there any elegant way by Swift to do that with the functional approach map, flatMap... or other modern Swift style

推荐答案

好的地图不是一个很好的例子,因为它与循环一样,你可以使用 reduce 来代替你将每个对象组合起来并转化为单个值:

Okay map is not a good example of this, because its just same as looping, you can use reduce instead, it took each of your object to combine and turn into single value:

let myDictionary = myArray.reduce([Int: String]()) { (dict, person) -> [Int: String] in
    var dict = dict
    dict[person.position] = person.name
    return dict
}

//[2: "b", 3: "c", 1: "a"]

这篇关于将对象数组映射到Swift中的Dictionary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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