Swift - Array.first(其中

时间:2017-10-14 12:55:12

标签: arrays swift xcode

我遇到了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"

3 个答案:

答案 0 :(得分:1)

"(userdata?.name)!"只是一个普通字符串,以左括号开头。这可能是你想要的。

"\(userdata?.name)!"是使用字符串插值的字符串。它将评估(userdata?.name)!如果userdatanil,则userdata?.namenil!会使其崩溃,这是故意的。

建议使用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

}