gpt4 book ai didi

casting - 获取包含特定键的 NSArray 中的所有 NSArray

转载 作者:行者123 更新时间:2023-11-28 07:16:37 28 4
gpt4 key购买 nike

我有一个 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 行崩溃,但它确实给出了错误:线程 1:EXC_BREAKPOINT(code=EXC_1386_BPT, subcode=0x0)

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

最佳答案

下标返回一个可选值 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 之间的桥接这一事实,您可以“swiftify”您的代码:

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

关于casting - 获取包含特定键的 NSArray 中的所有 NSArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25606596/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com