How to access value of __nssingleobjectarrayi in the following code

ぐ巨炮叔叔 提交于 2020-07-22 06:47:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!