Skip to content

Instantly share code, notes, and snippets.

@rbrockerhoff
Last active March 6, 2020 19:19
Show Gist options
  • Save rbrockerhoff/1d900ae02fe064c9c0f0 to your computer and use it in GitHub Desktop.
Save rbrockerhoff/1d900ae02fe064c9c0f0 to your computer and use it in GitHub Desktop.
Some useful extensions to Dictionary
extension Dictionary {
init (_ array: Array<Element>) {
self = [ : ]
self.merge(array)
}
mutating func merge (array: Array<Element>) {
for (key: KeyType, value: ValueType) in array {
self[key] = value
}
}
init <S: Sequence where S.GeneratorType.Element == Element> (_ seq: S) {
self = [ : ]
self.merge(seq)
}
mutating func merge <S: Sequence where S.GeneratorType.Element == Element> (seq: S) {
var gen = seq.generate()
while let (key: KeyType, value: ValueType) = gen.next() {
self[key] = value
}
}
}
// Example:
let nums = [0, 1, 2, 3]
let mp = map(nums, {($0 * 2, "“\($0)”")})
let dm = Dictionary(mp)
println(dm) // will print [0: “0”, 2: “1”, 4: “2”, 6: “3”]
// The merge functions act on an existing (mutable) Dictionary instead of
// returning a new one.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment