Skip to content

Instantly share code, notes, and snippets.

@rbrockerhoff rbrockerhoff/dictext.swift
Last active Dec 24, 2015

Embed
What would you like to do?
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
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.