Skip to content

Instantly share code, notes, and snippets.

@natecook1000
Created September 7, 2017 19:39
Show Gist options
  • Select an option

  • Save natecook1000/57f386bff5b748ed1ab55ff0a1016a86 to your computer and use it in GitHub Desktop.

Select an option

Save natecook1000/57f386bff5b748ed1ab55ff0a1016a86 to your computer and use it in GitHub Desktop.
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