Created
August 23, 2020 05:57
-
-
Save charlieInDen/aadbbcc5dd28dc166ab252043bf8d034 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 Collection { | |
/// Returns an array containing the results of mapping the given closure | |
/// over the sequence's elements. | |
/// | |
/// In this example, `map` is used first to convert the names in the array | |
/// to lowercase strings and then to count their characters. | |
/// | |
/// let cast = ["Vivien", "Marlon", "Kim", "Karl"] | |
/// let lowercaseNames = cast.map { $0.lowercased() } | |
/// // 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"] | |
/// let letterCounts = cast.map { $0.count } | |
/// // 'letterCounts' == [6, 6, 3, 4] | |
/// | |
/// - Parameter transform: A mapping closure. `transform` accepts an | |
/// element of this sequence as its parameter and returns a transformed | |
/// value of the same or of a different type. | |
/// - Returns: An array containing the transformed elements of this | |
/// sequence. | |
@inlinable | |
public func map<T>( | |
_ transform: (Element) throws -> T | |
) rethrows -> [T] { | |
// TODO: swift-3-indexing-model - review the following | |
let n = self.count | |
if n == 0 { | |
return [] | |
} | |
var result = ContiguousArray<T>() | |
result.reserveCapacity(n) | |
var i = self.startIndex | |
for _ in 0..<n { | |
result.append(try transform(self[i])) | |
formIndex(after: &i) | |
} | |
_expectEnd(of: self, is: i) | |
return Array(result) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment