Skip to content

Instantly share code, notes, and snippets.

@tjeerdintveen
Created July 30, 2020 15:57
Show Gist options
  • Save tjeerdintveen/82888946cca62e7915acb8affdc5c233 to your computer and use it in GitHub Desktop.
Save tjeerdintveen/82888946cca62e7915acb8affdc5c233 to your computer and use it in GitHub Desktop.
import Cocoa
extension Collection {
func firstMap<T>(_ transform: @escaping (Element) -> T?) -> T? {
for element in self {
if let transformed = transform(element) {
return transformed
}
}
return nil
}
}
let values = ["a", "b", "3"]
let result = values.firstMap { string in
return Int(string)
}
print(result) // Optional(3)
@tjeerdintveen
Copy link
Author

@escaping can be left out actually

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment