首页 > 解决方案 > 如何根据条件从结构数组中快速检索键列表?

问题描述

如何获取包含以下代码中存在的员工姓名的数组?我正在寻找使用地图或过滤器的简单单行解决方案。

struct Employee {
    var name: String?
    var present: Bool?
}

var employeeList = [Employee]()

employeeList.append(Employee(name: "A", present:true))
employeeList.append(Employee(name: "B", present:false))
employeeList.append(Employee(name: "C", present:false))
employeeList.append(Employee(name: "D", present:true))

// Get the list of employees who have present == true
// Should return ["A", "D"]

标签: iosarraysswiftstruct

解决方案


尝试

let res = employeeList.compactMap { $0.present ? $0.name : nil } 

?如果您始终提供值,请删除struct属性


推荐阅读