Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 使用map创建一个对象数组,该数组包含其他对象数组的少量对象属性_Swift - Fatal编程技术网

Swift 使用map创建一个对象数组,该数组包含其他对象数组的少量对象属性

Swift 使用map创建一个对象数组,该数组包含其他对象数组的少量对象属性,swift,Swift,假设我们有一个像这样的Employee类 class Employee { var id: String? var name: String? var role: String? var age: Int? var salary: Int? } var employeeList: [Employee] 我必须从employeeList创建一个新的对象数组,其中只包含一些属性(例如:id、name、age) 除了使用for循环来迭代employeeLis

假设我们有一个像这样的Employee

class Employee {
    var id: String?
    var name: String?
    var role: String?
    var age: Int?
    var salary: Int?
}

var employeeList: [Employee]
我必须从
employeeList
创建一个新的对象数组,其中只包含一些属性(例如:id、name、age)

除了使用for循环来迭代
employeeList

类似的内容之外,还有其他方法(如map)吗

let myData: [(String?, String?, Int?)] = employeeList.map { ($0.id, $0.name, $0.age) }

虽然不确定为什么您的
id
String
类型。。。通常ID为
Int

如果要使用
map
,可以执行以下操作:

class Employee {
    var id: String?
    var name: String?
    var role: String?
    var age: Int?
    var salary: Int?
}

var employeeList: [Employee]

var employeeModifiedList = employeeList.map {
    (id: $0.id, name: $0.name, age: $0.age)
}

您可以使用
map
它本质上是一个
for
循环,您可以映射多个属性并创建单个数组。或者,您可以使用forEach对所有内容进行迭代,并将其加载到您创建的任何数组中,这样一来,拥有所有可选字段是一个非常大的代码味道。如果一个员工的id、姓名、角色、年龄和薪水都为零,这到底意味着什么?那将是一个奇怪的同事。“你多大了?”“零。”