我遇到了userdataArray.first(where....)
的问题。基本上,我的目标是基于userdata
提取userId
以填充单元格。
变量userdata
包含一个数组。但是,当我尝试使用userdata?.name
配置单元格时,模拟器会出错。
我做错了什么?不是userdata
数组,还是嵌套数组?
viewController
中的代码:
let userdata = userdataArray.first(where:{$0.userId == activity.userId})
print("Array filter test")
dump(userdata)
let image = UIImage(named: "profile_image")
cell.configureCell(profileImage: image!, profileName: "(userdata?.name)!", activityDate: "8 October", name: activity.name, distance: "8 km", sightings: activity.sightings, kills: activity.kills)
return cell
Xcode的输出和错误:
Array filter test
▿ Optional(Shoota_MapKit.Userdata)
▿ some: Shoota_MapKit.Userdata #0
- userId: "NhZZGwJQCGe2OGaNTwGvpPuQKNA2"
- name: "Christian"
- city: "Oslo"
- country: "Norway"
- profileImage: "profile_image"
答案 0 :(得分:1)
"(userdata?.name)!"
只是一个普通字符串,以左括号开头。这可能是不你想要的。
"\(userdata?.name)!"
是使用字符串插值的字符串。它将评估(userdata?.name)!
如果userdata
为nil
,则userdata?.name
为nil
,!
会使其崩溃,这是故意的。
建议使用if let ...
或guard let ...
,如果找不到该项,请使用其他代码。
答案 1 :(得分:1)
确保您拥有用户数据:
guard let userdata = userdataArray.first(where:{$0.userId == activity.userId}),
let image = UIImage(named: "profile_image") else {
//no userdata
return cell
}
cell.configureCell(profileImage: image, profileName: userdata.name, activityDate: "8 October", name: activity.name, distance: "8 km", sightings: activity.sightings, kills: activity.kills)
return cell
答案 2 :(得分:0)
@shallowThought:谢谢你的帮助。我最终得到了以下,似乎工作。
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "feedCell") as? feedCell else {
print("dequeueResuableCell return an else"); return UITableViewCell()
}
let activityDict = activityArray[indexPath.row]
guard let userdata = userdataArray.first(where:{$0.userId == activityDict}) else {return cell}
let image = UIImage(named: userdata.profileImage)
cell.configureCell(profileImage: image!, profileName: userdata.name, activityDate: "8 October", name: activityDict.name, distance: "8 km", sightings: activityDict.sightings, kills: activityDict.kills)
return cell
}