Created
May 7, 2021 11:15
-
-
Save gcbrueckmann/4f7b261d37fe70983fcb94199bf953f8 to your computer and use it in GitHub Desktop.
Fans of the zip(_:_:) function may find that the opposite operation, while easy to implement using reduce(into:), is arguably not as readable. The unzip(_:) function helps with that.
This file contains hidden or 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
/// Creates a pair of sequences built out of an underlying sequence of pairs, i.e. the inverse of `zip(_:_:)`. | |
/// | |
/// let wordsAndNumbers = [ | |
/// ("one", 1), | |
/// ("two", 2), | |
/// ("three", 3), | |
/// ("four", 4) | |
/// ] | |
/// | |
/// let unzipped = unzip(wordsAndNumbers) | |
/// // unzipped == (["one", "two", "three", "four"], [1, 2, 3, 4]) | |
/// | |
/// - Parameters: | |
/// - sequence: The sequence or collection to unzip. | |
/// - Returns: A tuple pair of sequences, where the elements of each sequence are the first and second elements, respectively, of the corresponding elements of `sequence`. | |
func unzip<E1, E2, S: Sequence>(_ sequence: S) -> ([E1], [E2]) where S.Element == (E1, E2) { | |
sequence.reduce(into: ([E1](), [E2]())) { | |
$0.0.append($1.0) | |
$0.1.append($1.1) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment