【问题标题】:Fast and efficient way to get a Dictionary "key" based its "values" which is an array of Strings in Swift快速有效地获取基于其“值”的字典“键”,它是 Swift 中的字符串数组
【发布时间】:2021-10-26 23:04:42
【问题描述】:

我正在使用 Swift 进行编程,并且有一个如下所示的字典,可以将公司的员工映射到他们的部门:

var acmeInc: [String: [String]] = [
    
    "marketing"  : ["john", "amanda", "peter"],
    "operations" : ["anna", "teresa", "jack", "tom", "nigel", "katy"],
    "sales"      : ["bill", "jill"]
]

我想创建一个返回员工所在部门的函数。因此,该函数接受员工姓名并返回他们工作的部门。最快、最有效的方法是什么?或者甚至不应该首先使用字典并使用其他数据结构?

func printDepartmentOfEmployee(employee: String)
{
  ...   
  
  print("\(employee) works in department \(...)")
}

我能想到的最简单的“蛮力”方法是让一个大字典将每个员工映射到每个部门,但想看看是否有更好的方法。

最好的方法是什么?

【问题讨论】:

  • 按键查找速度很快。按值查找不存在。因此,如果根据名称了解部门对您来说很重要,那么使用按部门键入的字典一开始就很愚蠢。重新开始并重新评估您的需求。
  • 问题是员工多,部门少,所以才想到用这种结构。也许使用字典不是正确的数据结构。
  • 我不相信有“蛮力”搜索。我唯一能想到的就是避免创建另一个字典。您可以遍历字典中的键,在该数组中搜索该键并继续搜索,直到找到该人。
  • 这意味着您不必“复制”已有的信息。

标签: arrays swift performance dictionary


【解决方案1】:

你还没有说你认为你会去哪里。但总的来说,请相信对象。使用结构,而不是字典,尽量不要使用硬编码的字符串,除非你必须——例如,如果知道有限数量的部门类型,使用枚举。这是一个例子:

enum Department {
    case marketing, operations, sales
}
struct Employee {
    let name: String
    let department: Department
}
struct Corporation {
    var employees = [Employee]()
}

以下是我们如何构建您在示例中使用的“相同”数据:

let employees : [Employee] = [
    .init(name: "john", department: .marketing),
    .init(name: "amanda", department: .marketing),
    .init(name: "peter", department: .marketing),
    .init(name: "anna", department: .operations),
    .init(name: "teresa", department: .operations),
    .init(name: "jack", department: .operations),
    .init(name: "tom", department: .operations),
    .init(name: "nigel", department: .operations),
    .init(name: "katy", department: .operations),
    .init(name: "bill", department: .sales),
    .init(name: "jill", department: .sales),
]
var acme = Corporation()
acme.employees = employees

想想这种安排的好处。给定一个员工,我们现在立即知道该员工的部门——它是员工的department

如果您确实需要查找与员工姓名对应的部门,那也很容易。同样,如果您需要某个部门的员工。我们只是给公司一些简单的方法来做这些事情:

extension Corporation {
    func departmentOfEmployee(named name: String) -> Department? {
        employees.first(where: {$0.name == name})?.department
    }
    func employeesInDepartment(_ department: Department) -> [Employee] {
        employees.filter {$0.department == department}
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-27
    相关资源
    最近更新 更多