Last active
December 17, 2018 04:41
-
-
Save garohussenjian/03ea8c5af6fedfb9d1b78ec5d7290dd8 to your computer and use it in GitHub Desktop.
Sequence extensions for KeyPath
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 Sequence { | |
/// Map over properties of sequence elements | |
/// ``` | |
/// let counts = ["Hello", "World!"].map(\.count) | |
/// // returns [5, 6] | |
/// ``` | |
/// | |
/// - Returns: An array of element properties at the keypath | |
@inlinable | |
public func map<U>(_ keyPath: KeyPath<Element, U>) -> [U] { | |
return map { $0[keyPath: keyPath] } | |
} | |
/// Map and flatten over sequence properties of sequence elements | |
/// ``` | |
/// let subviews = [view1, view2].flatMap(\.subviews) | |
/// // returns an array combining the subviews of view1 and view2 | |
/// ``` | |
/// | |
/// - Returns: An array of element values at the keypath | |
@inlinable | |
public func flatMap<S: Sequence>(_ keyPath: KeyPath<Element, S>) -> [S.Element] { | |
return flatMap { $0[keyPath: keyPath] } | |
} | |
/// Map and compact over optional properties of sequence elements | |
/// ``` | |
/// let initials = ["Key", "Value", "Coding"].compactMap(\.first) | |
/// // returns ["K", "V", "C"] | |
/// ``` | |
/// | |
/// - Returns: An array of element values at the keypath | |
@inlinable | |
public func compactMap<U>(_ keyPath: KeyPath<Element, U?>) -> [U] { | |
return compactMap { $0[keyPath: keyPath] } | |
} | |
/// Map and compact over optional properties of optional sequence elements | |
/// ``` | |
/// let words = ["Three", nil, "Little", "", "Birds"].compactMap(\.first) | |
/// // returns ["T", "L", "B"] | |
/// ``` | |
/// | |
/// - Returns: An array of element values at the keypath | |
@inlinable | |
public func compactMap<T, U>(_ keyPath: KeyPath<T, U?>) -> [U] where Element == T? { | |
return compactMap { $0?[keyPath: keyPath] } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment