Enthuziast Enthuziast - 3 days ago 5
Swift Question

Check if object is part of list

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?

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