Skip to content

Instantly share code, notes, and snippets.

@mikeger
Created November 8, 2023 14:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikeger/81fe636b1d804d9e4beeb076b04c7354 to your computer and use it in GitHub Desktop.
Save mikeger/81fe636b1d804d9e4beeb076b04c7354 to your computer and use it in GitHub Desktop.
Return first element that passes the mapping
extension Collection {
public func firstMap<T>(where predicate: (Element) throws -> T?) rethrows -> T? {
for element in self {
if let value = try predicate(element) {
return value
}
}
return nil
}
}
let collection = ["A", "B", "1", "C"]
let first = collection.firstMap { str in
Int(str)
}
print(first)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment