Skip to content

Instantly share code, notes, and snippets.

@joemasilotti
Last active December 14, 2015 22:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joemasilotti/40309e18af962b59df4d to your computer and use it in GitHub Desktop.
Save joemasilotti/40309e18af962b59df4d to your computer and use it in GitHub Desktop.
Swift Array to Dictionary
//: Playground - noun: a place where people can play
struct Option {
var id: UInt
var name: String
}
func combine(options: [Option]) -> [UInt: String] {
var combinedOptions = [UInt: String]()
for option in options {
combinedOptions[option.id] = option.name
}
return combinedOptions
}
let option1 = Option(id: 1, name: "One")
let option2 = Option(id: 2, name: "Two")
let option3 = Option(id: 3, name: "Three")
combine([option1, option2, option3]) // [2: "Two", 3: "Three", 1: "One"]
@joemasilotti
Copy link
Author

Is there a better way?

@JessyCatterwaul
Copy link

There's not a better built-in way, but I use this:

[option1, option2, option3].Dictionary{($0.id, $0.name)}

Support for that is here:
https://gist.github.com/Jessy-/cf7afb4819fe1a542712

It's modeled after https://msdn.microsoft.com/en-us/library/bb548657(v=vs.110).aspx but tuples make it slightly better.

@westerlund
Copy link

you can do something like this:

let arr = [option1, option2, option3]
let reduced = arr.reduce([:]) { (var dict, e) -> [Int: String] in
    dict[e.id] = e.name
    return dict
}

I typed this in the phone with autocorrect on, may not compile out of the box!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment