首页 > 解决方案 > 设置变量等于 if 语句条件

问题描述

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

 if pinArray.contains(where: {$0.title == restaurantName})

我将如何创建这个元素的变量?我尝试过

 let thePin = pinArray.contains(where: {$0.title == restaurantName}) 

但这带有“无法将布尔值转换为 MKAnnotation”。

我也尝试过

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

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

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

在此处输入图像描述

标签: swiftif-statementvar

解决方案


contains(where:)返回一个Bool指示是否找到匹配项。它不返回匹配的值。

然后你尝试强制转换为当然会崩溃的thePina也是如此。BoolMKAnnotation

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

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

contains根本不需要。无需强制转换(假设pinArray是一个数组MKAnnotation)。


推荐阅读