Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if object is part of list

Tags:

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

This does not work in Swift, what is the correct operator?

like image 325
Enthuziast Avatar asked Jul 08 '14 19:07

Enthuziast


2 Answers

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"
}
like image 190
Kevin Avatar answered Oct 29 '22 17:10

Kevin


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
    }
}
like image 28
vladof81 Avatar answered Oct 29 '22 16:10

vladof81