如何检查任何对象类型的2D数组是否包含swift中的内容

时间:2015-03-24 18:31:17

标签: arrays swift contains

我有一个声明为var cellitemcontent:[[AnyObject]] = []

的二维数组

我在其中存储了一个字符串和bool值([apple,false; banana,false; egg,true])

当我尝试查看cellitemcontent是否包含任何错误值时,我会这样做:

if cellitemcontent[0][1] as Bool == false {} //fatal error: Cannot index empty buffer

或者如果我尝试:

if contains((cellitemcontent[0][1] as Bool), false) {} //Type 'Bool' does not conform to protocol 'SequenceType'

P.S:我把它作为AnyObject而不是元组的原因是因为我将它保存到NSUserDefaults并且我被告知你不能保存默认值。

3 个答案:

答案 0 :(得分:1)

你永远不应该将Bool类型与true进行比较。这是多余的。你可以这样做:

if (cellitemcontent[0][1] as Bool) {
    // your code
}

或者如果您想检查它是否为假,只需在它前面添加一个感叹号:

if !(cellitemcontent[0][1] as Bool) {
    // your code
}

//

var cellitemcontent:[[AnyObject]] = []

cellitemcontent.append(["apple", false])
cellitemcontent.append(["banana", false])
cellitemcontent.append(["egg", true])

for index in 0..<cellitemcontent.count {
    if !(cellitemcontent[index][1] as Bool) {
        println("is false")   // (2 times)
    } else {
        println("is true")    // (1 time)
    }
}

答案 1 :(得分:1)

您还可以map cellItemContents到只有Bool值的数组 - 新数组的索引将匹配原始数组的索引:

let bools = cellItemContents.map { $0[1] as Bool }

使用[[apple, false], [banana, false], [egg, true]]的原始数组,您将获得一个新数组[false, false, true],您可以随意执行任何操作:

println(contains(bools, false))  // prints "true"

答案 2 :(得分:0)

除非您特别需要2D数组,否则您可能更容易使用字典:

let myDict = ["apple": false, "banana": false, "egg": true]

if myDict["apple"]! {
    println("The food is an apple.")
} else {
    println("The food is not an apple.") // Prints
}

if myDict["banana"]! {
    println("The food is an apple.")
} else {
    println("The food is not an apple.") // Prints
}

if myDict["egg"]! {
    println("The food is an apple.") // Prints
} else {
    println("The food is not an apple.")
}

在另一条评论中回答您的问题时,请按以下方式进行迭代:

for (food, value) in myDict {

    println("The \(food) is \(value)")
}
相关问题