如何根据存在的元素在字典上追加数组



打印菜单列表?[1]["subMenu"]

I got below message

▿ Optional<Any>
▿ some : 1 element
▿ 0 : 1 element
▿ 0 : 2 elements
- key : subItem
▿ value : 4 elements
▿ 0 : 7 elements
▿ 0 : 2 elements
- key : permission
- value : access
▿ 1 : 2 elements
- key : title
- value : Create
▿ 2 : 2 elements
- key : bar
- value : sidebar
▿ 3 : 2 elements
- key : isNotify
- value : 0
▿ 4 : 2 elements
- key : link
- value : linker
▿ 5 : 2 elements
- key : path
- value : /dashboard
▿ 6 : 2 elements
- key : icon
- value : add

尝试根据条件提取menuList?[i]["subMenu"]["subItem"],如果值存在,则附加到数组中,否则不存在。

少数情况下["subItem"]可能有0个元素

if let permissionList =  MenuList?[i]["subMenu"] {
let subMenu =  (permissionList as AnyObject)
if subMenu.count > 0 {
for j in 0..<subMenu.count{
let subItem =  subMenu["subItem"]
}
}

返回nil

On try subMenu[0]错误:"下标(_:)"使用不明确子菜单[0]

下面是George函数的一个变体,使用map操作而不是手卷循环来表示:

func menuResult() -> [String] {
// FIXME: Why is this even optional in the first place?
guard let menuList = menuList else { return [] }
return menuList.compactMap { menu -> [String] in
guard let subMenu = menu["subMenu"] as? [String: String] else { return nil }
return subMenu["subItem"]
}
}

例如menuData:

let menuList: [[String: Any]]? = [
["abc": [
"123": "test1",
"456": "test2"
]],
["def": [
"789": "test3",
"101112": "test4"
]],
["subMenu": [
"subItem": "Other correct path" // <- subMenu[2]["subMenu"]["subItem"]
]],
["subMenu": [
"otherItem": "WRONG",
"subItem": "CORRECT" // <- subMenu[3]["subMenu"]["subItem"]
]]
]

获取menuData[i]["subMenu"]["subItem"]menuData数组中所有项目的代码:

func menuResult() -> [String] {
// menuList can't start nil
guard let menuList = menuList else { return [] }
var result = [String]()
// Iterate every element of menuList
for i in menuList.indices {
// Get 'subMenu' dictionary if it exists
if let subMenu = menuList[i]["subMenu"] as? [String: String] {
// Get 'subItem' dictionary if it exists
if let subItem = subMenu["subItem"] {
// Store value at this path
result.append(subItem)
}
}
}
return result
}
print(menuResult())
// Prints: ["Other correct path", "CORRECT"]

相关内容

  • 没有找到相关文章

最新更新