设置变量等于 if 语句条件

Setting variable equal to if statement condition

我有一个 if 语句来检查数组元素是否与局部变量匹配。

 if pinArray.contains(where: {[=10=].title == restaurantName})

如何创建该元素的变量? 我尝试了

 let thePin = pinArray.contains(where: {[=11=].title == restaurantName}) 

但是 "could not cast boolean to MKAnnotation"。

我也尝试了

的变体
let pins = [pinArray.indexPath.row]
let pinn = pins(where: pin.title == restaurantName) (or close to it)

mapp.selectAnnotation(thePin as! MKAnnotation, animated: true)

无济于事。我缺少什么基本步骤?

contains(where:) returns a Bool 指示是否找到匹配项。它不 return 匹配值。

所以 thePin 是一个 Bool,然后您尝试将其强制转换为 MKAnnotation,这当然会崩溃。

如果您想要匹配值,请将您的代码更改为:

if let thePin = pinArray.first(where: { [=10=].title == restaurantName }) {
    do {
        mapp.selectionAnnotation(thePin, animated: true)
    } catch {
    }
} else {
    // no match in the array
}

根本不需要contains。无需转换(假设 pinArrayMKAnnotation 的数组)。