How to check if an element is in an array in the Swift example

This post is about checking if an element exists in an array in Swift with examples. It also includes checking object exists in an array of objects based on property.

  • Array Contains method to check an item exists in an array
  • Filter method to filter elements from an array, return an element if found.
  • Check object exists in the Array of Objects using the filter method

How to check if an element exists in a swift array with examples?

There are multiple ways to check if an object or element exists in an array.

  • Contains method
  • filter

Array contains method

The array contains a function that operates on sequence types.

It checks and returns true if a given element exists in A Sequence.

Here is a syntax

func contains(_ element: Self.Element) -> Bool

Here is an example to check if a number exists in an array of numbers

let numbers = [11, 12, 13, 14, 15]
print(numbers.contains(15)); // true
print(numbers.contains(6));// false

Here is an example to check given string exists in an array of strings

let words = ["one", "two", "three", "four"]
print(words.contains("one")) // true
print(words.contains("One")) // false
print(words.contains("five")) // false

It checks exact string match, not case-sensitive.

You can also check in the conditional statement with contains function.

let numbers = [11, 12, 13, 14, 15]


if numbers.contains(15) == true {
    print("Number Exists")
} else {
    print("Number Not Exist")
}

Array filter function

Array Filter functions check if the given element is found and returns the first element.

let numbers = [11, 12, 13, 14, 15]

var exists = numbers.filter({ $0 == 11 }).first
if exists != nil {
    print("Number Exists")
} else {
    print("Number Not Exist")
}

Check object exists in the Array of Objects in Swift

This checks if an object exists in an array of objects and returns true. Else false returned.

  • Create an Employee Struct object with ID and name fields.
  • Created an array of Employee objects.
  • Use the filter method to check whether an ID exists or not and return an object
  • use the if statement to check returned object
struct Employee
{
  let id:Int
  let name:String
  init (_id:Int, _name:String){
    self.id = id self.name = name
  }
}

let emps =[Employee (1, "john"), Employee (4, "krish"),
    Employee (2, "ram"), Employee (7, "eric"),
Employee (5, "andy"), Employee (10, "franc")]

let franc = Employee (10, "franc")
let exists = emps.first (where:{ $0.id == franc.id })

if  exists !=nil {
    print ("Found")
}
else{
    print ("Not Found")
  }