Enthuziast Enthuziast - 6 days ago 7
Swift Question

Check if object is part of list in Swift

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"
}
}


Swift doesn´t like this. But I cannot find the right operator... Any ideas?

Answer

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"
}