How to check if an element is contained in an array in Swift?
Hi everyone! I just started learning Swift and came across a seemingly simple task. I need to check if a certain value is in an array. For example, I have an array of strings with user names:
```swift
let users = ["Anna", "Boris", "Victor", "Galina"]
```
I want to write a condition: if the user "Boris" is in the list, then print "Access granted", otherwise — "User not found".
I tried using the `==` operator, but of course Swift gave an error because you can't compare an array with a single element. Then I wrote a `for-in` loop and checked each element manually:
```swift
var found = false
for user in users {
if user == "Boris" {
found = true
break
}
}
if found {
print("Access granted")
}
```
This works
No answers yet.
Log in to leave an answer
Blogs