Skip to content

Commit

Permalink
feat(Dictionary): add storing:by: init
Browse files Browse the repository at this point in the history
  • Loading branch information
marionauta committed May 23, 2021
1 parent d70cf2d commit 8d2b37d
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions Sources/HelperKit/Extensions/Dictionary.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,34 @@ extension Dictionary {

self = result
}

/// Creates a new dictionary whose keys are the properties returned by the
/// given closure and whose values are the elements that returned each key.
///
/// If two elements return the same key, only one will be kept. The closure
/// should return a unique enough key, like an ID.
///
/// struct Book: Identifiable {
/// let id: Int
/// let name: String
/// }
///
/// let books = [Book(id: 1, name: "One"), Book(id: 2, name: "Two"), Book(id: 3, name: "Three")]
/// let dict1 = Dictionary(storing: books, by: \.id)
/// // [1: Book(id: 1, name: "One"), 2: Book(id: 2, name: "Two")]
/// let dict2 = Dictionary(storing: books, by: { $0.name.count * 2 })
/// // [6: Book(id: 2, name: "Two"), 10: Book(id: 3, name: "Three")]
///
/// - Parameters:
/// - values: A sequence of values to store in a dictionary.
/// - keyForValue: A closure that returns a key for each element in `values`.
@inlinable public init<S>(storing values: S, by keyForValue: (S.Element) -> Key) where S: Sequence, S.Element == Value {
var result: [Key: Value] = [:]

for value in values {
result[keyForValue(value)] = value
}

self = result
}
}

0 comments on commit 8d2b37d

Please sign in to comment.