Skip to content

Instantly share code, notes, and snippets.

@indyfromoz
Forked from tjeerdintveen/firstMap.swift
Created July 30, 2020 18:32
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 indyfromoz/46b6b35136300e20b0af129140f64a65 to your computer and use it in GitHub Desktop.
Save indyfromoz/46b6b35136300e20b0af129140f64a65 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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment