如果你正在处理一个NSDictionary
,希望在NSDictionary
进入嵌套值时KVC方法.valueForKey
另一种是.valueForKeyPath
,非常有用。
let foo : (NSDictionary, String) -> (String?) = {
($0.valueForKeyPath($1+".username") as? NSArray)?.reduce($1+" ->") {$0+" "+($1 as! String)}
}
print(foo(data, "A") ?? "Key not found") // A -> AAA ABB
print(foo(data, "B") ?? "Key not found") // B -> BBB ABC
print(foo(data, "C") ?? "Key not found") // Key not found
使用data
:
var data : NSDictionary = [
"A": [["userid":"1","username":"AAA","usergroupid":"2"], ["userid":"33","username":"ABB","usergroupid":"8"]],
"B": [["userid":"2","username":"BBB","usergroupid":"8"], ["userid":"43","username":"ABC","usergroupid":"8"]]
]
为了回答您的其他问题
要vadian:的答案,你写道:
“谢谢你的回答,我还有一个问题,
A: username AAA userid 1 , username ABB userid 2
“
可以解决这个例如利用zip
结合上面使用的KVC技术。一种解决方案如下
let bar : (NSDictionary, String) -> (String?) = {
dict, key in
guard let
uName = ((dict.valueForKeyPath(key+".username") as? NSArray)?.map { String($0) }),
uId = ((dict.valueForKeyPath(key+".userid") as? NSArray)?.map { String($0) }) else {
return nil
}
var foo = Array(zip(uName,uId)).reduce(key+": ") { $0 + "username: " + $1.0 + " userid: " + $1.1 + ", " }
foo.removeRange(foo.endIndex.advancedBy(-2)..<foo.endIndex)
return foo
}
print(bar(data, "A") ?? "Key not found")
// A: username: AAA userid: 1, username: ABB userid: 33
print(bar(data, "B") ?? "Key not found")
// B: username: BBB userid: 2, username: ABC userid: 43
print(bar(data, "C") ?? "Key not found")
// Key not found
转到“字典”。该文档使用示例和一切:) https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes。HTML – boidkan
也是真的不是一个NSDictionary – boidkan