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

lastIndex(of:)

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

Declaration 宣言

func lastIndex(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 last index where element is found. If element is not found in the collection, this method returns nil. そこでelementが見つけられた最後のインデックス。elementがコレクションの中に見つけられないならば、このメソッドはnilを返します。

Discussion 解説

After using lastIndex(of:) to find the position of the last instance 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. lastIndex(of:)を使って特定の要素の最後のインスタンスの位置をあるコレクションの中で見つけた後、あなたは添え字によって要素にアクセスするのにそれを使うことができます。この例が示すのは、どうやってあなたが学生らの配列の中の名前の1つを修正できるかです。


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

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