Arrays 根据数组中文本的变化指定图像

Arrays 根据数组中文本的变化指定图像,arrays,swift,Arrays,Swift,我正在根据标签的名称指定图像。例如,如果标签上写着“Car”,那么指定的图像就是“CarImage”,我让它使用以下代码: if cell.nameLabel.text == “Car” { if let image = UIImage(named: “CarImage”) { cell.imageView?.image = image } } 我希望能够为同一图像设置标签的许多变体。我正在使用数组尝试此操作: if cell.nameLabel.text == [“Ca

我正在根据标签的名称指定图像。例如,如果标签上写着“Car”,那么指定的图像就是“CarImage”,我让它使用以下代码:

  if cell.nameLabel.text == “Car” {
  if let image = UIImage(named: “CarImage”)
  { cell.imageView?.image = image 
  }
  }
我希望能够为同一图像设置标签的许多变体。我正在使用数组尝试此操作:

if cell.nameLabel.text == [“Car”, “Automobile”, “Auto”, "Vehicle",] {
if let image = UIImage(named: “Car”)
{ cell.imageView?.image = image 
  }
  }
然而,我已经尝试了几种不同的方法,它不起作用。我读过好几个不同的答案,但似乎没有一个干净的方法可以做到这一点。谢谢你的任何意见

let array = ["Car", "Automobile", "Auto", "Vehicle"]
if array.contains(where: {cell.nameLabel.text != nil && $0 == cell.nameLabel.text!}) {
   cell.imageView.image = UIImage(named: "CarImage")
}
array.contains(其中:{cell.namelab.text!=nil&&$0==cell.namelab.text!})
将检查
[“Car”、“Auto”、“Auto”、“Vehicle”]
数组中的任何字符串是否在
cell.namelab.text
中具有该字符串。如果是,请在单元格上设置图像

你可以想象这样做:

cell.imageView.image = array
      .first(where: {cell.nameLabel.text != nil && $0 == cell.nameLabel.text!})
      .flatMap({_ in UIImage(named: "CarImage")})

谢谢你的回复。我收到错误“条件中的变量绑定需要初始值设定项”