{

How to check the element index of a list or array in the swift example


This tutorial explains how to find the index of an element in an array of swift programming languages.

Below, Shows the find the index of an element types.

  • primitive array
  • Array of Objects

Array provides two methods [firstIndex](https://developer.apple.com/documentation/swift/array/firstindex(of:)) and [lastIndex](https://developer.apple.com/documentation/swift/array/lastindex(where:)) that returns the index position forward iteration and reverse iteration.

Both methods return nil if no element is found in an array.

How to find the element index for an array of numbers in swift

The array contains a list of strings. The

The firstIndex method returns the first occurrence element position in an array. The lastIndex method returns the last occurrence element position of an array.

Both these methods contain where the class is compared with a given string using the == operator. Here is an example

let numbers = ["one","two","three"]
let index1 = numbers.firstIndex(where: {$0 == "one"}) as Any
var index2 = numbers.lastIndex(where: {$0 == "two"}) as Any
var index3 = numbers.lastIndex(where: {$0 == "five"}) as Any
print(index1)
print(index2)
print(index3)

Output:

Optional(0)
Optional(1)
nil

How to find an object index in an array of objects in Swift?

In this example, a Class of objects is created and assigned in an array.

index methods compared with given object id using == operator and returns index position.

It returns nil if an object is not found.

Here is an example

class Student {
    var marks: Int =  0
    var id: Int;
    init ( _ id: Int , _ marks: Int){
        self.marks = marks
        self.id=id
    }
}

let students = [Student(1,70),Student(2,50),Student(3,90)]
var index1 = students.firstIndex{ $0.id == 1 } as Any
print(index1)
var index2 = students.firstIndex{ $0.id == 6 } as Any
print(index2)

Output:

Optional(0)
nil
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.