Created
September 7, 2017 19:39
-
-
Save natecook1000/57f386bff5b748ed1ab55ff0a1016a86 to your computer and use it in GitHub Desktop.
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
| extension Sequence { | |
| /// Returns an array with the transformed elements of the sequence if all | |
| /// the transformations succeed. | |
| func flatMapAll<T>(_ transform: (Element) -> T?) -> [T]? { | |
| var result: [T] = [] | |
| result.reserveCapacity(underestimatedCount) | |
| for element in self { | |
| if let transformed = transform(element) { | |
| result.append(transformed) | |
| } else { | |
| return nil | |
| } | |
| } | |
| return result | |
| } | |
| } | |
| let valid = ["1", "2", "3", "4"] | |
| print(valid.flatMapAll(Int.init)) | |
| // Optional([1, 2, 3, 4]) | |
| let invalid = ["1", "2", "blah", "4"] | |
| print(invalid.flatMapAll(Int.init)) | |
| // nil |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment