Instance Method インスタンスメソッド

firstIndex(where:)

Returns the first index in which an element of the collection satisfies the given predicate. 最初のインデックスで、それにおけるコレクションの要素が与えられた述部を満足させるものを返します。

Declaration 宣言

func firstIndex(where predicate: (Base.Element) throws -> Bool) rethrows -> Index?

Parameters パラメータ

predicate

A closure that takes an element as its argument and returns a Boolean value that indicates whether the passed element represents a match. あるクロージャ、それは1つの要素をそれの引数として取り、渡された要素が合致するものであるかどうかを指し示すブール値を返します。

Return Value 戻り値

The index of the first element for which predicate returns true. If no elements in the collection satisfy the given predicate, returns nil. それに対してpredicatetrueを返す最初の要素のインデックス。コレクションの要素が与えられた述部を満たすことがないならば、nilを返します。

Discussion 解説

You can use the predicate to find an element of a type that doesn’t conform to the Equatable protocol or to find an element that matches particular criteria. Here’s an example that finds a student name that begins with the letter “A”: あなたは述部を使って、Equatableプロトコルに準拠しない型の要素を見つける、または特定の基準に合致する要素を見つけることができます。ここに、文字「A」で始まる生徒名を見つける例があります:


let students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
if let i = students.firstIndex(where: { $0.hasPrefix("A") }) {
    print("\(students[i]) starts with 'A'!")
}
// Prints "Abena starts with 'A'!"

Complexity: O(n), where n is the length of the collection. 計算量:O(n)、ここでnはコレクションの長さです。