Created
November 8, 2023 14:30
-
-
Save mikeger/81fe636b1d804d9e4beeb076b04c7354 to your computer and use it in GitHub Desktop.
Return first element that passes the mapping
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 { | |
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