Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

array
swift
communitycreator

What is lastIndex(of:) array method in Swift?

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

We can use the lastIndex(of:) method to return the last index of a specified array element.

Syntax

arr.lastIndex(of: element)

Parameters

element: This is the element to search for in the array or collection.

Return value

This method returns the last index of a given element in an array. Otherwise, it returns nil.

Code example

// create arrays
let numbers = [2, 6, 5, 3, 6]
let twoLetterWords = ["up", "go", "me", "go", "up", "on"]
let names = ["John", "James", "Theodore", "Theodore"]
// get index of some elements
let result1 = numbers.lastIndex(of : 6)!
let result2 = twoLetterWords.lastIndex(of: "go")!
let result3 = names.lastIndex(of: "Theodore")!
// print results
print(result1) // 4
print(result2) // 3
print(result3) // 3
Get Index of last element

Explanation

  • Lines 2-3: We create a few arrays.
  • Lines 7-9: We get the index of the elements specified using the lastIndex(of:) method and store the results in some variables.
  • Lines 12-14: We print our results.

RELATED TAGS

array
swift
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring