Reputation: 399
I am having an issue with userdataArray.first(where....)
. Basically, I am aiming to pull out userdata
for a message based on the userId
to populate a cell.
The variable userdata
contains an array. However when I try to configure the cell with userdata?.name
the simulator gives an error.
What am I doing wrong? isn't userdata
an array, or is it a nested array?
Code in 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
Output and error from Xcode:
Array filter test
▿ Optional(Shoota_MapKit.Userdata)
▿ some: Shoota_MapKit.Userdata #0
- userId: "NhZZGwJQCGe2OGaNTwGvpPuQKNA2"
- name: "Christian"
- city: "Oslo"
- country: "Norway"
- profileImage: "profile_image"
Upvotes: 0
Views: 4073
Reputation: 399
@shallowThought: Thanks for the help. I ended up with the below, it seems to work.
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
}
Upvotes: 0
Reputation: 52538
"(userdata?.name)!"
is just a plain string, starting with an opening parenthesis. That's probably not what you wanted.
"\(userdata?.name)!"
is a string using string interpolation. It will evaluate (userdata?.name)!
If userdata
is nil
, then userdata?.name
is nil
, and the !
will make it crash, which is intentional.
It recommend to use if let ...
or guard let ...
and use some alternative code if the item is not found.
Upvotes: 1
Reputation: 19602
Make sure you have user data:
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
Upvotes: 1