To check if two arrays are equal in Swift, you can use the ==
operator for arrays with the same elements and manually compare elements for arrays with different elements.
In this example,
arr1
and arr2
with the same elements.==
operator to check if the arrays are equal and store the result in the variable equal1
.==
operator checks if two arrays have the same elements in the same order.equal1
to the console.let arr1 = [1, 2, 3]
let arr2 = [1, 2, 3]
let equal1 = arr1 == arr2
print("Arrays are equal: \(equal1)")
Arrays are equal: true
In this example,
arr3
and arr4
with different elements.equal2
.equal2
is set to true
; otherwise, it's set to false
.equal2
to the console.let arr3 = [1, 2, 3]
let arr4 = [3, 2, 1]
var equal2 = true
for i in 0..<arr3.count {
if arr3[i] != arr4[i] {
equal2 = false
break
}
}
print("Arrays are equal: \(equal2)")
Arrays are equal: false
In this tutorial, we learned How to check if Two Arrays are Equal in Swift language with well detailed examples.