获取包含特定Key的NSArray中的所有NSArrays

时间:2014-09-01 13:07:59

标签: casting swift nsarray

我有一个输出以下内容的NSArray:

(
    {
    category = 1;
    categoryname = Random;
    excuse = "Enter your excuse here";
    id = 1;
    name = Jo;
},
    {
    category = 2;
    categoryname = School;
    excuse = "Enter your excuse here";
    id = 2;
    name = Jo;
},
    {
    category = 2;
    categoryname = School;
    excuse = "Enter your excuse here";
    id = 3;
    name = if;
}
)

现在您可以看到,category有不同的值。我正在通过Int我要与category值进行比较,只检索另一个NSArray中某个类别中的对象。

这是我的代码:

func getAllExcusesData(categoryID: Int) -> NSMutableArray {
    var arr: NSMutableArray = NSMutableArray()
    for excuse in allExcusesData {
        println(excuse["category"]) // this line outputs "Optioanl(x)" - x is either 1 or 2, depending on what index I pass through
// it crashes here, at the 'if' line
        if excuse["category"] as Int == categoryID {
            var e: NSArray = excuse as NSArray
            arr.addObject(excuse)
        }
    }
    return arr
}

它在if行崩溃,但确实会出错: Thread 1:EXC_BREAKPOINT(code=EXC_1386_BPT, subcode=0x0)

如何将对象的category字段与给定索引进行比较,然后将该字段添加到将从方法返回的新数组中?

1 个答案:

答案 0 :(得分:1)

下标返回一个可选值AnyObject? - 您必须在转换它之前将其解包或者通过以下方式之一与另一个值进行比较:

if let excuseCategory: AnyObject = excuse["category"]? {
    if excuseCategory as Int == categoryID {
        // do sth
    }
}

// or if you're absolutely sure that "category" key always exists:

if excuse["category"]! as Int == categoryID {
    // do sth
}

考虑到ArrayNSArrayNSMutableArray之间桥接的事实,您可以“解密”您的代码:

func getAllExcusesData(categoryID: Int) -> NSArray {
    return (allExcusesData as [AnyObject]).filter({ excuse in
        return excuse["category"]! as Int == categoryID
    })
}