【问题标题】:How to retrieve list of keys based on condition on value from struct array in swift?如何根据条件从结构数组中快速检索键列表?
【发布时间】:2020-08-19 01:41:14
【问题描述】:

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

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

【问题讨论】:

    标签: ios arrays swift struct


    【解决方案1】:

    试试

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-26
      • 2018-08-24
      • 1970-01-01
      相关资源
      最近更新 更多