问题
I parsed a json and got a JSON Dictionary.
{
data = (
{
bio = "<null>";
bookmarked = 35;
id = 22;
"last_seen" = {
date = "2017-03-30 14:00:01";
timezone = "Asia/Kolkata";
"timezone_type" = 3;
};
name = "Alex";
username = "Alex";
}
);}
I am trying to access username and date. I tried it doing
let name = userData.value(forKeyPath: "data.username")
print(username)
By printing this, I am getting a __NSSingleObjectArrayI with the username.
Optional(<__NSSingleObjectArrayI 0x6080000120b0>(
Alex
)
)
How do I access that and display at other places? Basically extract the "Alex" from that as a String?
回答1:
value(forKeyPath
applied to an array containing dictionaries returns an array – as revealed in the output. You need to get the first item of the array
let names = userData.value(forKeyPath: "data.username")
if !names.isEmpty { print(names[0]) }
However the usual way to get the name is
if let data = userDatavalue["data") as? [[String:Any]], !data.isEmpty,
let username = data[0]["username"] as? String {
print(username)
}
来源:https://stackoverflow.com/questions/43112592/how-to-access-value-of-nssingleobjectarrayi-in-the-following-code