Tip: Doing more than two partitions for a Sequence (or Collection)

While researching in our archives for something else, I saw a post about getting both sub-sequences of a filter, something I've occasionally wondered about. I decided to try it, and use a Dictionary return, and found out:

extension Sequence {

    /// Categorizes the elements with the mappings from the given hash function,
    /// keeping elements sharing a category in the same relative order in the
    /// given type of value collections.
    /// - Precondition: The sequence is finite.
    /// - Parameter partitionType: A meta-type specifier for the collection
    ///   bundling elements sharing a category.
    /// - Parameter hash: A hashing function, mapping an element to a category.
    /// - Returns: A dictionary where each key is a result of `hash` from at
    ///   least one element and the corresponding value is all of the elements
    ///   that matched that key, still in their relative order from this
    ///   sequence.
    /// - Complexity: ???
    public func hashIntoPartitions<T: RangeReplaceableCollection, K: Hashable>(ofType partitionType: T.Type, along hash: (Element) throws -> K) rethrows -> [K: T] where T.Element == Element {
        return try Dictionary(grouping: self, by: hash).mapValues { T($0) }


that we already added it! You don't need the method above if you don't care about customizing the Value to be something besides Array.

Terms of Service

Privacy Policy

Cookie Policy