按名称在数组中访问属性

时间:2015-07-07 18:11:49

标签: swift

如果我有以下设置:

struct Job {
    let jobDescription: String
    let days: [String]
    let hourlyPay: Double
}

var jobArray = [
    Job(jobDescription: "Dog Walker", days:  ["Monday", "Wednesday", "Friday"], hourlyPay: 7),
    Job(jobDescription: "Babysitter", days:  ["Tuesday", "Wednesday"], hourlyPay: 15),
    // etc
]

或者只是一个数组(没有结构):

var jobArray = [
        ("Dog Walker", ["Monday", "Wednesday", "Friday"], "7"),
        ("Babysitter", ["Tuesday", "Wednesday"], "15"),
        ("Leaves Raker", ["Sunday", ""], "10")
        ]

如果我知道工作描述,有没有办法让我参考连接到它的其他属性,而无需通过循环测试每个工作描述来查看它是否匹配?

所以,而不是:

for (name, days, salary) in jobArray {
  if name == "Babysitter" {
     print(salary)
  }
}

我从一开始就知道我想要哪个名字,并且可以在没有循环的情况下参考其薪水。

1 个答案:

答案 0 :(得分:2)

如果您可以使用Array,我认为您也可以使用Dictionary

var jobs = [
  "Dog Walker"    : (["Monday", "Wednesday", "Friday"], 7),
  "Babysitter"    : (["Tuesday", "Wednesday"], 15),
  "Leaves Raker"  : (["Sunday", ""], 10)
]

if let (days, rate) = jobs["Babysitter"] {
  println("Babysitter hourly rate \(rate) on \(days)")
}

在[星期二,星期三] 打印保姆小时费率15。

如果您对Swift 2感兴趣,可以将代码转换为以下内容:

var jobs = [
  "Dog Walker"    : (["Monday", "Wednesday", "Friday"], 7),
  "Babysitter"    : (["Tuesday", "Wednesday"], 15),
  "Leaves Raker"  : (["Sunday", ""], 10)
]

func printJobDescription(job: String) {
  guard let (days, rate) = jobs[job] else {
    return
  }

  print("\(job) hourly rate \(rate) on \(days)")
}

printJobDescription("Babysitter")