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

firstIndex(of:)

Returns the first index where the specified value appears in the collection. 指定された値がコレクションにおいて現れるところの最初のインデックスを返します。

Declaration 宣言

func firstIndex(of element: Base.Element) -> Index?
Available when Base.Element conforms to Equatable. Base.ElementEquatableに準拠する時に利用可能です。

Parameters パラメータ

element

An element to search for in the collection. このコレクションにおいて捜される要素。

Return Value 戻り値

The first index where element is found. If element is not found in the collection, returns nil. elementが見つけられたところの最初のインデックス。elementがコレクションの中に見つけられないならば、nilを返します。

Discussion 解説

After using firstIndex(of:) to find the position of a particular element in a collection, you can use it to access the element by subscripting. This example shows how you can modify one of the names in an array of students. firstIndex(of:)を使って特定の要素の位置をあるコレクションの中で見つけた後、あなたは添え字によって要素にアクセスするのにそれを使うことができます。この例が示すのは、どうやってあなたが学生らの配列の中の名前の1つを修正できるかです。


var students = ["Ben", "Ivy", "Jordell", "Maxime"]
if let i = students.firstIndex(of: "Maxime") {
    students[i] = "Max"
}
print(students)
// Prints "["Ben", "Ivy", "Jordell", "Max"]"

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