FirstNonNil.swift 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. //===----------------------------------------------------------------------===//
  2. //
  3. // This source file is part of the Swift Algorithms open source project
  4. //
  5. // Copyright (c) 2020 Apple Inc. and the Swift project authors
  6. // Licensed under Apache License v2.0 with Runtime Library Exception
  7. //
  8. // See https://swift.org/LICENSE.txt for license information
  9. //
  10. //===----------------------------------------------------------------------===//
  11. //===----------------------------------------------------------------------===//
  12. // firstNonNil(_:)
  13. //===----------------------------------------------------------------------===//
  14. extension Sequence {
  15. /// Returns the first non-`nil` result obtained from applying the given
  16. /// transformation to the elements of the sequence.
  17. ///
  18. /// let strings = ["three", "3.14", "-5", "2"]
  19. /// if let firstInt = strings.firstNonNil({ Int($0) }) {
  20. /// print(firstInt)
  21. /// // -5
  22. /// }
  23. ///
  24. /// - Parameter transform: A closure that takes an element of the sequence as
  25. /// its argument and returns an optional transformed value.
  26. /// - Returns: The first non-`nil` return value of the transformation, or
  27. /// `nil` if no transformation is successful.
  28. ///
  29. /// - Complexity: O(*n*), where *n* is the number of elements at the start of
  30. /// the sequence that result in `nil` when applying the transformation.
  31. @inlinable
  32. public func firstNonNil<Result>(
  33. _ transform: (Element) throws -> Result?
  34. ) rethrows -> Result? {
  35. for value in self {
  36. if let value = try transform(value) {
  37. return value
  38. }
  39. }
  40. return nil
  41. }
  42. }