5

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?

Otávio
  • 735
  • 11
  • 23
Enthuziast
  • 1,195
  • 1
  • 10
  • 18
  • 1
    use `if contains(Friends, Name)`. I swear this is a dupe... see http://stackoverflow.com/questions/24037699/swift-arrays-and-contains-crashes-when-var-is-string-but-when-i-cast-it-to-st – Jack Jul 08 '14 at 19:07

3 Answers3

3

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"
}
Kevin
  • 53,822
  • 15
  • 101
  • 132
1

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
    }
}
vladof81
  • 26,121
  • 9
  • 38
  • 41
1

The Swift 3 way to do it:

let name = "Tim"
let friends = ["Jim", "Tim", "Anna", "Emma"]
var i = ""
if friends.contains(name) {
    i = "Is a friend"
} else {
    i = "Not a friend"
}
mikepj
  • 1,256
  • 11
  • 11