Last active
December 14, 2015 22:04
-
-
Save joemasilotti/40309e18af962b59df4d to your computer and use it in GitHub Desktop.
Swift Array to Dictionary
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: 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"] |
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.
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
Is there a better way?