swift - Accessing properties by name in array -
if have following setup:
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 ] or array (without struct):
var jobarray = [ ("dog walker", ["monday", "wednesday", "friday"], "7"), ("babysitter", ["tuesday", "wednesday"], "15"), ("leaves raker", ["sunday", ""], "10") ] if know job description, there way me refer other properties connected without having go through loop testing each job description see if matches?
so, instead of:
for (name, days, salary) in jobarray { if name == "babysitter" { print(salary) } } i know name want outset , can refer salary without loop.
if can use array, assume can use dictionary well.
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)") } it prints babysitter hourly rate 15 on [tuesday, wednesday].
if you're interested in swift 2 well, can transform code this:
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")
Comments
Post a Comment