Advanced-NSOperations/Earthquakes/Operations/Dictionary+Operations.swift
2022-02-16 22:16:09 -08:00

31 lines
1.1 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this samples licensing information
Abstract:
A convenient extension to Swift.Dictionary.
*/
extension Dictionary {
/**
It's not uncommon to want to turn a sequence of values into a dictionary,
where each value is keyed by some unique identifier. This initializer will
do that.
- parameter sequence: The sequence to be iterated
- parameter keyer: The closure that will be executed for each element in
the `sequence`. The return value of this closure, if there is one, will
be used as the key for the value in the `Dictionary`. If the closure
returns `nil`, then the value will be omitted from the `Dictionary`.
*/
init<Sequence: SequenceType where Sequence.Generator.Element == Value>(sequence: Sequence, @noescape keyMapper: Value -> Key?) {
self.init()
for item in sequence {
if let key = keyMapper(item) {
self[key] = item
}
}
}
}