在以下代码中如何访问__nssingleobjectarrayi的值 [英] How to access value of __nssingleobjectarrayi in the following code

查看:595
本文介绍了在以下代码中如何访问__nssingleobjectarrayi的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我解析了一个json并得到了一个JSON字典.

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)

通过打印此内容,我得到了带有用户名的__NSSingleObjectArrayI.

By printing this, I am getting a __NSSingleObjectArrayI with the username.

Optional(<__NSSingleObjectArrayI 0x6080000120b0>(
Alex
)
)

我如何访问它并在其他地方显示?基本上从中提取"Alex"作为字符串吗?

How do I access that and display at other places? Basically extract the "Alex" from that as a String?

推荐答案

value(forKeyPath应用于包含字典的数组将返回一个数组-如输出所示.您需要获取数组的第一项

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)
}

这篇关于在以下代码中如何访问__nssingleobjectarrayi的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆