我收到如下服务响应
[["realms": ({
authorizationType = External;
contentPageId = "<null>";
description = "Demo accounts";
externalRegistrationUrl = "<null>";
id = 1;
identifier = Demo;
showDuringSignup = 1;
}), "identifier": MENIISRE, "name": MegaTest, "imageData": < null > , "iconFilename": < null > , "imageDataId": 0, "id": 1, "orderIndex": 0, "altName": < null > ],
["realms": ({
authorizationType = Internal;
contentPageId = "<null>";
description = Test Desc;
externalRegistrationUrl = "<null>";
id = 2;
identifier = TestFB;
showDuringSignup = 0;
}), "identifier": 0012321, "name": TestAccount, "imageData": < null > , "iconFilename": a385bdff - 323 d - 4 a4b - 8019 - 233115 b43b38.png, "imageDataId": 1000019, "id": 2, "orderIndex": 0, "altName": < null > ]]
从上面的响应中,我只需要显示那些“showDuringSignup”为 1 的记录。
一个选项是我可以在数组上运行 for 循环并获得所需的结果,但这是一种旧方法,我想使用高阶函数(例如 Filter、Map、flapMap 等)
因此我尝试了下面的代码
let arrayOfAvailableBanks = arrayOfDictOfBankAccounts.map{$0["realms"].map{($0["showDuringSignup"] as? Int) == 1}}
但我无法获得所需的输入。
请建议我在这里做错了什么,以及如何只获取 'showDuringSignup' 为 1 的那些对象。
最佳答案
你应该使用filter
来代替,请在下面找到代码,
let arrayOfAvailableBanks = realms.filter { (dict) -> Bool in
return dict.contains(where: { (arg) -> Bool in
if arg.key == "realms", let value = arg.value as? [String: Any] {
if let internalValue = value["showDuringSignup"] as? Int, internalValue == 1 {
return true
}
return false
}
return false
})
}
所以整个代码就是这样
let realms = [["realms": [
"authorizationType": "External",
"contentPageId": nil,
"description": "Demo accounts",
"externalRegistrationUrl": "<null>",
"id": 1,
"identifier": "Demo",
"showDuringSignup": 1],
"identifier": "MENIISRE", "name": "MegaTest", "imageData": nil , "iconFilename": nil , "imageDataId": 0, "id": 1, "orderIndex": 0, "altName": nil ],
["realms": [
"authorizationType": "Internal",
"contentPageId": nil,
"description": "Test Desc",
"externalRegistrationUrl": nil,
"id": 2,
"identifier": "TestFB",
"showDuringSignup": 0],
"identifier": 0012321, "name": "TestAccount", "imageData": nil , "iconFilename": "a385bdff - 323 d - 4 a4b - 8019 - 233115 b43b38.png", "imageDataId": 1000019, "id": 2, "orderIndex": 0, "altName": nil ]]
let arrayOfAvailableBanks = realms.filter { (dict) -> Bool in
return dict.contains(where: { (arg) -> Bool in
if arg.key == "realms", let value = arg.value as? [String: Any] {
if let internalValue = value["showDuringSignup"] as? Int, internalValue == 1 {
return true
}
return false
}
return false
})
}
print(arrayOfAvailableBanks)
关于swift - 在 Swift 中从 Array of Dictionary of Array 中过滤项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53704113/