From ba6a46f7933deb383241fc4699d539d83effcbab Mon Sep 17 00:00:00 2001 From: david-swift Date: Mon, 30 Sep 2024 09:44:17 +0200 Subject: [PATCH] Add asynchronous first index function --- Sources/Model/Extensions/Array.swift | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/Sources/Model/Extensions/Array.swift b/Sources/Model/Extensions/Array.swift index c369e6c..06e844a 100644 --- a/Sources/Model/Extensions/Array.swift +++ b/Sources/Model/Extensions/Array.swift @@ -111,6 +111,21 @@ extension Array { return nil } + /// Returns the index of the first element of the sequence that satisfies the given predicate. + /// - Parameter predicate: A closure that takes an element of the sequence as its argument + /// and returns a Boolean value indicating whether the element is a match. + /// - Returns: The index of the first element of the sequence that satisfies `predicate`, + /// or `nil` if there is no element that satisfies `predicate`. + public func firstIndex(where predicate: (Element) async throws -> Bool) async rethrows -> Int? { + for (index, element) in enumerated() { + let matches = try await predicate(element) + if matches { + return index + } + } + return nil + } + /// Returns the last element of the sequence that satisfies the given predicate. /// - Parameter predicate: A closure that takes an element of the sequence as its argument /// and returns a Boolean value indicating whether the element is a match.