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 中的特定元组?


- UITextView 内容插图 2022-01-01
- GPS状态的广播接收器? 2022-01-01
- SetOnItemSelectedListener上的微调程序错误 2022-01-01
- 网上有没有好的 UIScrollView 教程? 2022-01-01
- 使用自动布局向 UIScrollView 添加动态大小的视图 2022-01-01
- Xcode 7.3 中带有 UILabel 的 UIStackView 2022-01-01
- 如何在 iPhone 模拟器中重置 NSUserDefaults 数据? 2022-01-01
- URL编码Swift iOS 2022-01-01
- 在 Iphone SDK 的导航栏上添加多个按钮 2022-01-01
- 类似于 Mail.app 的 iPad 模态视图控制器? 2022-01-01