mirror of
https://github.com/apple/swift-algorithms
synced 2026-11-24 04:17:48 +00:00
* Add Sequence.firstNonNil(of:) and associated tests * Rename First.swift to FirstTests.swift * Address PR comments by adding guide and changing naming * Address PR comments by changing name * Update Guides/FirstNonNil.md Co-authored-by: Xiaodi Wu <13952+xwu@users.noreply.github.com> * Update Sources/Algorithms/FirstNonNil.swift Co-authored-by: Xiaodi Wu <13952+xwu@users.noreply.github.com> Co-authored-by: Xiaodi Wu <13952+xwu@users.noreply.github.com>
29 lines
987 B
Swift
29 lines
987 B
Swift
//===----------------------------------------------------------------------===//
|
|
//
|
|
// This source file is part of the Swift Algorithms open source project
|
|
//
|
|
// Copyright (c) 2020 Apple Inc. and the Swift project authors
|
|
// Licensed under Apache License v2.0 with Runtime Library Exception
|
|
//
|
|
// See https://swift.org/LICENSE.txt for license information
|
|
//
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
// firstNonNil(_:)
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
public extension Sequence {
|
|
/// Returns the first element in `self` that `transform` maps to a `.some`.
|
|
func firstNonNil<Result>(
|
|
_ transform: (Element) throws -> Result?
|
|
) rethrows -> Result? {
|
|
for value in self {
|
|
if let value = try transform(value) {
|
|
return value
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
}
|