我收到如下服务响应
[["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的那些记录。
一个选项是我可以在数组上运行循环并获得所需的结果,但这是一种旧方法,并且我想使用高阶函数(例如Filter,Map,flapMap等)
因此我尝试使用以下代码
let arrayOfAvailableBanks = arrayOfDictOfBankAccounts.map{$0["realms"].map{($0["showDuringSignup"] as? Int) == 1}}
但我无法获得所需的输入。
请提出我在这里做错了什么以及如何仅获取'showDuringSignup'为1的那些对象。
答案 0 :(得分:3)
您应该改用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)
答案 1 :(得分:1)
好吧,我想我可能已经解码了您提供的回复。
您这里需要的是filter
。
您可以尝试以下方法:
let array = // Your response here
let filtered = array.filter {
if let realms = $0["realms"] as? [String : Any],
let showDuringSignUp = realms["showDuringSignup"] as? Int { // Change Int if necessary
return showDuringSignUp == 1 // Change compared value as necessary
}
return false
}