Ios 如何根据swift中结构数组的值条件检索键列表?

Ios 如何根据swift中结构数组的值条件检索键列表?,ios,arrays,swift,struct,Ios,Arrays,Swift,Struct,如何获取包含以下代码中present为true的员工姓名的数组?我正在寻找使用map或filter的简单单线解决方案 struct Employee { var name: String? var present: Bool? } var employeeList = [Employee]() employeeList.append(Employee(name: "A", present:true)) employeeList.append(Employee(name: "B

如何获取包含以下代码中present为true的员工姓名的数组?我正在寻找使用map或filter的简单单线解决方案

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"]
试一试

如果总是提供值,请删除
结构的

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