To check if two arrays have the same elements regardless of order in Swift, you can sort both arrays and then compare them using the ==
operator.
In this example,
arr1
and arr2
with the same elements but in different order.sorted()
method.==
operator.let arr1 = [1, 2, 3]
let arr2 = [3, 1, 2]
let sortedArr1 = arr1.sorted()
let sortedArr2 = arr2.sorted()
let isEqual = sortedArr1 == sortedArr2
print(isEqual)
true
In this example,
arr3
and arr4
with different elements.sorted()
method.==
operator.let arr3 = [1, 2, 3]
let arr4 = [4, 5, 6]
let sortedArr3 = arr3.sorted()
let sortedArr4 = arr4.sorted()
let isEqual = sortedArr3 == sortedArr4
print(isEqual)
false
In this tutorial, we learned How to check if Two Arrays have Same Elements (Regardless of Order) in Swift language with well detailed examples.