How do I check if an array of tuples contains a particular one in Swift?(如何检查元组数组是否包含 Swift 中的特定元组?)
问题描述
考虑以下 Swift 代码.
Consider the following Swift code.
var a = [(1, 1)]
if contains(a, (1, 2)) {
println("Yes")
}
我只需要检查 a
是否包含元组,但代码会导致错误.
All I need is to check if a
contains the tuple but the code leads to error.
找不到接受参数列表的包含"的重载类型为'([(Int, Int)], (Int, Int))'
Cannot find an overload for 'contains' that accepts an argument list of type '([(Int, Int)], (Int, Int))'
为什么会这样以及如何正确使用contains
?
Why so and how to use contains
properly?
推荐答案
将以下内容添加到您的代码中:
Add the following to your code:
func contains(a:[(Int, Int)], v:(Int,Int)) -> Bool {
let (c1, c2) = v
for (v1, v2) in a { if v1 == c1 && v2 == c2 { return true } }
return false
}
当涉及到元组时,Swift 并不是那么灵活.它们不符合 Equatable
协议.所以你必须定义它或使用上面的函数.
Swift is not that flexible when it comes to tuples. They do not conform to the Equatable
protocol. So you must define that or use the above function.
这篇关于如何检查元组数组是否包含 Swift 中的特定元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何检查元组数组是否包含 Swift 中的特定元组?


基础教程推荐
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- iOS4 创建后台定时器 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01