gpt4 book ai didi

ios - 在 Swift 中循环遍历嵌入式 JSON 数组?

转载 作者:行者123 更新时间:2023-11-28 10:52:35 24 4
gpt4 key购买 nike

我正在尝试遍历嵌入式 JSON 数组并提取所有值以放入本地数组。这是 JSON 的样子:

"welcome": {
"data": {
"tncUrl": ""
},
"items": [
{
"newUser": [
{
"stepConcept": false
},
{
"stepSafety": true
},
{
"stepFacilitator": true
},
{
"stepTransparency": true
}
],
"switcher": [
{
"stepConcept": true
},
{
"stepSafety": true
},
{
"stepFacilitator": true
},
{
"stepTransparency": true
}
]
}
]
}

我能够看到我正在检索“newUser”的值,问题是遍历这些值并将它们添加到数组中。这样做时出现 EXC_BAD_INSTRUCTION 错误。这是我用来获取这些值的代码:

  func prepareArrayOfViews(userType: User)
{
if (welcomeJSON != nil)
{
let items : NSArray? = welcomeJSON!.value(forKey: "items") as? NSArray

if (items == nil)
{
listOfViews = ["stepConcept", "stepSafety", "stepFacilitator", "stepTransparency"]
maxPages = listOfViews.count
return
}

if (items != nil) {

if let newUser = (items?.value(forKey: "newUser") as? NSArray){

//Below is where the error "EXC_BAD_INSTRUCTION"
for key in (newUser as! NSDictionary).allKeys
{
if (((newUser as! NSDictionary).value(forKey: key as! String) as? Bool)!)
{
listOfViews.append(key as! String)
}
}

}

if (listOfViews.count == 0)
{
listOfViews = ["stepConcept", "stepSafety", "stepFacilitator", "stepTransparency"]
}

maxPages = listOfViews.count
}
}
}

最佳答案

我已将您的代码更改为使用原生 Swift 结构。由于当您的可选解包不起作用时您没有处理错误或做任何事情,我也将解包更改为 guard 语句。

除了 Swift 编码实践的严重问题外,您的问题是您试图将字典数组作为简单字典进行迭代。

func prepareArrayOfViews(userType: User){
guard let welcomeJSON = welcomeJSON else {return}
guard let items = welcomeJSON["items"] as? [[String:Any]] else {
listOfViews = ["stepConcept", "stepSafety", "stepFacilitator", "stepTransparency"]
maxPages = listOfViews.count
return
}
for item in items {
if let newUser = item["newUser"] as? [[String:Any]] {
for embeddedDict in newUser {
for (key, value) in embeddedDict {
if let val = value as? Bool, val == true {
listOfViews.append(key)
}
}
}
} else if let switcher = item["switcher"] as? [[String:Any]]{
for embeddedDict in switcher {
for (key, value) in embeddedDict {
if let val = value as? Bool, val == true {
//do whatever you need to with the value
}
}
}
}
}
if (listOfViews.count == 0){
listOfViews = ["stepConcept", "stepSafety", "stepFacilitator", "stepTransparency"]
}
maxPages = listOfViews.count
}

关于ios - 在 Swift 中循环遍历嵌入式 JSON 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45391947/

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