检查对象是否是列表的一部分

时间:2014-07-08 19:01:04

标签: swift

我试图弄清楚变量是否是数组的一部分。

这是代码:

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中不起作用,什么是正确的运算符?

3 个答案:

答案 0 :(得分:3)

使用方法find,它返回(可选的)元素的索引,或contains,它只返回一个BOOL。另外,使用小写字母启动本地变量名称。大写应该只是class / struct / protocol / etc.名。

let name = "Tim"
var i = ""
let friends = ["Jim", "Tim", "Anna", "Emma"]
if find(friends, name) {
    i = "Is a Friend"
} else {
    i = "Not a Friend"
}

答案 1 :(得分:1)

除了Jack Wu和Kevin的帖子,你还可以尝试通过迭代数组的粗暴方式,尝试以下方法:

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

答案 2 :(得分:1)

Swift 3的方法:

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