Expand the firstNonNil(_:) docs (#115)

* Fix indentation

* Improve documentation
This commit is contained in:
Tim Vermeulen authored and GitHub committed 2021-03-29 19:18:56 +02:00
1 parent 0065c60a22
commit 001247f8a5
2 files changed
+82 -25

No files matched your search

+22 -7
View File
@@ -14,15 +14,30 @@
//===----------------------------------------------------------------------===//
public extension Sequence {
/// Returns the first element in `self` that `transform` maps to a `.some`.
/// Returns the first non-`nil` result obtained from applying the given
/// transformation to the elements of the sequence.
///
/// let strings = ["three", "3.14", "-5", "2"]
/// if let firstInt = strings.firstNonNil({ Int($0) }) {
/// print(firstInt)
/// // -5
/// }
///
/// - Parameter transform: A closure that takes an element of the sequence as
/// its argument and returns an optional transformed value.
/// - Returns: The first non-`nil` return value of the transformation, or
/// `nil` if no transformation is successful.
///
/// - Complexity: O(*n*), where *n* is the number of elements at the start of
/// the sequence that result in `nil` when applying the transformation.
func firstNonNil<Result>(
_ transform: (Element) throws -> Result?
) rethrows -> Result? {
for value in self {
if let value = try transform(value) {
return value
}
}
return nil
for value in self {
if let value = try transform(value) {
return value
}
}
return nil
}
}