我为标题道歉。我知道这是Swift中的常见问题。我在其他帖子中阅读了答案,我相信我更接近于解决问题。
我有一系列词典var userObjects: [[String:AnyObject]] = []
我正在使用它来填充集合视图。在我的cellForItemAt函数中,我有
guard let user = userObjects[indexPath.row]["data"] as? [String:AnyObject] else { return cell }
guard let firstName = user["first_name"] else {return cell}
我在上面的代码段中的第二行中收到典型的Type 'Any' has no subscript members
错误,直到我将as? [String:AnyObject]
添加到代码段的第一行。问题是现在代码在user
的第一个保护语句中断,好像该语句不正确。
我做错了什么,以及如何正确施放物品?
userObjects
中元素的示例:
{
count = 1;
data = (
{
email = "tester2@test.com";
"first_name" = Tester;
gender = Male;
instagram = "n/a";
"last_name" = One;
preference = Female;
profileImageURL = "n/a";
}
);
page = 0;
pageCount = 1;
perPage = 20;
答案 0 :(得分:1)
当你说
时guard let user = userObjects[indexPath.row]["data"] as? [String:AnyObject] else { return cell }
...您说user
是"data"
条目:
data = (
{
email = "tester2@test.com";
"first_name" = Tester;
gender = Male;
instagram = "n/a";
"last_name" = One;
preference = Female;
profileImageURL = "n/a";
}
);
那不是字典。它是字典的数组。因此,用"first_name"
下标它的尝试失败了。
答案 1 :(得分:1)
根据您的用户数据,数据是键值对的数组,所以首先您必须从字典中获取数据,然后您需要从数据(字典数组)中获取对象,如下所示:
您可以下标[[String:AnyObject]]类型的值: -
# for d in $(ls -1 /dev/sd?) ; do is_frozen=$(hdparm -I $d | grep frozen) ; echo $d $is_frozen ; done
/dev/sda frozen
/dev/sdb not frozen
答案 2 :(得分:0)
您必须将userObjects[indexPath.row]
投射到Dictionary
let userData = userObjects[indexPath.row] as? [String:Any]
guard let user = userData?["data"] as? [String:Any] else { return cell }
guard let firstName = user["first_name"] else {return cell}