I am trying to figure out whether a variable is part of an array.
This is the code:
let Name = "Tim"
var i = ""
let Friends = ["Jim", "Tim", "Anna", "Emma"]
if Name in Friends {
i = "Is a Friend"
} else {
i = "Not a Friend"
}
This does not work in Swift, what is the correct operator?
Use the method find
, which returns (an optional with) the element's index, or contains
, which just returns a BOOL. Also, start local variable names with lowercase letters. Uppercase should only be class/struct/protocol/etc. names.
let name = "Tim"
var i = ""
let friends = ["Jim", "Tim", "Anna", "Emma"]
if find(friends, name) {
i = "Is a Friend"
} else {
i = "Not a Friend"
}
In addition to Jack Wu and Kevin's posts, you can also try brute way of iterating through array, try following approaches:
let Name = "Tim"
let Friends = ["Jim", "Tim", "Anna", "Emma"]
// iterate through Friends
for f1 in Friends {
if f1 == Name {
println(f1)
break
}
}
// enumerate Friends
for (i, f2) in enumerate(Friends) {
if f2 == Name {
println("Item \(i + 1): \(f2)")
break
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With