Last active
March 6, 2020 19:19
-
-
Save rbrockerhoff/1d900ae02fe064c9c0f0 to your computer and use it in GitHub Desktop.
Some useful extensions 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
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