Created
April 25, 2018 16:48
-
-
Save erica/888cf55457ee600ca1582935a3fb8172 to your computer and use it in GitHub Desktop.
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 { | |
/// Returns an array created by applying an instance | |
/// method to each element of a source sequence. | |
/// This method address the problem caused by mapping | |
/// instance methods: | |
/// | |
/// ["a", "b", "c"].map(String.uppercased) | |
/// | |
/// This statement returns `[(Function), (Function), (Function)]`, | |
/// which is essentially `[{ String.uppercased("a"), ... }]` | |
/// An instance method is `Type.method(instance)()`. Using | |
/// `mapApply` forces each partial result to execute and returns those | |
/// results, producing ["A", "B", "C"] as expected. | |
/// | |
/// ["a", "b", "c"].mapApply(String.uppercased) // ["A", "B", "C"] | |
/// | |
/// Thanks, Malcolm Jarvis, Gordon Fontenot | |
/// | |
/// - Parameter transform: The partially applicable instance method | |
/// - Parameter element: The sequence element to be transformed by the | |
/// applied method | |
/// - Returns: An array containing the results of applying the method | |
/// to each value of the source sequence | |
public func mapApply<T>(_ transform: (_ element: Element) throws -> () -> T) rethrows -> [T] { | |
return try map(transform).map({ $0() }) | |
} | |
/// Returns an array created by applying a keypath to | |
/// each element of a source sequence. | |
/// | |
/// let keyPath = \String.count | |
/// ["hello", "the", "sailor"].map(keyPath) // 5, 3, 6 | |
/// | |
/// Thanks, Malcolm Jarvis, Gordon Fontenot | |
/// | |
/// - Parameter keyPath: A keyPath on the `Element` | |
/// - Returns: An array containing the results of applying | |
/// the keyPath to each element of the source sequence. | |
public func map<T>(_ keyPath: KeyPath<Element, T>) -> [T] { | |
return map({ $0[keyPath: keyPath] }) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment