swift - 设置变量等于 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)
无济于事。我缺少什么基本步骤?
解决方案
contains(where:)
返回一个Bool
指示是否找到匹配项。它不返回匹配的值。
然后你尝试强制转换为当然会崩溃的thePin
a也是如此。Bool
MKAnnotation
如果您想要匹配值,请将您的代码更改为:
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
)。
推荐阅读
- ios - 如何估计 Realm DB 大小
- r - 第 2 部分:如何在 ggplot 的条形图上按值正确排序段
- algorithm - 创建自定义链表的边缘案例
- amazon-web-services - 获取 Cognito 用户时放大 AWS API 函数问题
- javascript - 承诺第二次没有解决
- visual-studio - 如何在 VS 2019 中构建一个深色 UI 应用程序?
- javascript - Node.js 如何在浏览器中使用警报消息
- influxdb - 如何在kapacitor中发送任务名称而不是警报ID?
- c - 从 PostgreSQL C 函数写入文件
- reactjs - 当数组未更改时,在每次渲染中调用 useEffect 数组依赖项