swift - 使用自定义对象映射

标签 swift

我有一些东西

let one = Person(name: "Joe", age:20)
let two = Person(name: "Phil", age:21)
let three = Person(name: "Moe", age:21)

然后我有一个数组

let array = [one, two, three]

现在我需要创建一个新数组,它将只包含年龄为 21 岁的人。

我试试

var newArray : [Person] = array.map ({ $0.age = 21 })

但是编译器说他不能转换结果类型 '_?'到预期类型 [Person]

我做错了什么?

最佳答案

试试这个:

var newArray : [Person] = array.filter {$0.age == 21}

map 只是修改您的数组。它不会删除元素。

关于swift - 使用自定义对象映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41694655/

相关文章:

ios - 如何使用 SWIFT 检查 IOS 应用程序是否首次运行

swift - 如何避免在 RealmSwift 中迁移

swift - 使用字符串数组用 UIButtons 填充 UIStackView

swift - Swift 中的 Curried 闭包

swift - 在哪些情况下 SKNode 上的 runAction 无法完成?

swift - 从 struct init 中提取函数

ios - 如何仅显示 SwiftUI 列表中选定的项目?

swift - 平铺背景图像

objective-c - Swift 中的 UIButton 帮助

string - Swift 生成器 : What is the counterpart to next()?