当iOS中此变量包含Null时,如何将Any对象类型的变量转换为String?

时间:2018-10-13 07:03:04

标签: json swift

问题是当我想将用户变量转换为字符串时,它说log。可能是因为用户对象包含null。

响应:

subcategory

代码:

const data = ['{"entries":[{"name":"sample","id":"8d"},{"name":"sample","id":"57"},{"name":"sample","id":"acc"}]}\n',
    '{"entries":[{"name":"sample","id":"8d"},{"name":"sample","id":"50"},{"name":"sample","id":"ac"}]}\n',
    '{"entries":[{"name":"sample","id":"8d"},{"name":"sample","id":"50"},{"name":"sample","id":"ac"}]}\n',
    '{"entries":[{"name":"sample","id":"8d"},{"name":"sample","id":"50"}]}\n',
];

// Let us first format it correctly 
const formatted = data.map(x => {
    return JSON.parse(x.trim())
});

// Let's loop over our newly created array and push unique values into a new one

let uniqueNames = [];
let uniqueObj = [];

for(let i = 0; i < formatted.length; i++){    
    if(uniqueNames.indexOf(data[i]._id) === -1){
       uniqueObj.push(data[i])
       uniqueNames.push(data[i]._id);
       }        
    }

// Let's take that one step further and display it exactly as you wanted it to be :)
const iterator = uniqueObj.values();

for (const value of iterator) {
   console.log(value);
}

1 个答案:

答案 0 :(得分:2)

我看到的是您的user对象被声明为Any。尝试将其设置为字典。

guard let responseDict = response["data"] as? [String : Any],
    let user = responseDict["user"] as? [String : Any] else {
        // There is no user
        return
}

if let userEmail = user["email"] as? String {
    print(userEmail)
    // Can be a result as "<null>" because of server result
}
if let firstName = user["firstName"] as? String {
    print(firstName)
    // Can be a result as "<null>" because of server result
}

我还可以添加@Vadian所说的内容。责怪网站的所有者发送真实的null值,而不是字符串化的null。