ios - 将对象数组映射到 Swift 中的字典

标签 ios arrays swift dictionary

我有一组 Person 的对象:

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

数组是:

let myArray = [p1,p1,p3]

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

var myDictionary =  [Int:String]()

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

Swift 是否有任何优雅的方式来使用函数式方法 mapflatMap... 或其他现代 Swift 风格来做到这一点

最佳答案

Swift 4 开始,您可以使用 reduceinto 版本更干净高效地执行@Tj3n 的方法它摆脱了临时字典和返回值,因此阅读起来更快更容易。

示例代码设置:

struct Person { 
    let name: String
    let position: Int
}
let myArray = [Person(name:"h", position: 0), Person(name:"b", position:4), Person(name:"c", position:2)]

Into 参数传递的结果类型为空字典:

let myDict = myArray.reduce(into: [Int: String]()) {
    $0[$1.position] = $1.name
}

直接返回传入中的类型的字典:

print(myDict) // [2: "c", 0: "h", 4: "b"]

关于ios - 将对象数组映射到 Swift 中的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38454952/

相关文章:

ios - 快速检测 Sprite 节点是否存在

Swift:将 ALAsset 复制到应用程序的文档目录中

ios - 如何最好地将原始像素数据转换为 PNG 文件?

php - 在 Laravel 中使用 Eloquent 通过 Foreach 循环反转数组元素的顺序

javascript - 将字符串连接到数组的每个非空元素

python - 如何在 python 中的换行符处拆分字符串?

ios - Swift - AVPlayer 通过 UISlider 取得进展

iphone - 使用cocos2d的等距平铺游戏中的问题

ios - 使用 NSTimer 触发上一个 Controller 上的方法

ios - 支持多选和时刻 View 的 UIImagePickerController 替代品