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 中的特定元组?
基础教程推荐
- UIImage 在开始时不适合 UIScrollView 2022-01-01
- 为什么姜饼模拟器方向卡在应用程序中? 2022-01-01
- 如何将图像从一项活动发送到另一项活动? 2022-01-01
- 如何比较两个 NSDate:哪个是最近的? 2022-01-01
- Android Volley - 如何动画图像加载? 2022-01-01
- iOS - UINavigationController 添加多个正确的项目? 2022-01-01
- Play 商店的设备兼容性问题 2022-01-01
- SwiftUI-ScrollViewReader的ScrollTo不滚动 2022-01-01
- navigationItem.backBarButtonItem 不工作?为什么上一个菜单仍然显示为按钮? 2022-01-01
- Xcode UIView.init(frame:) 只能在主线程中使用 2022-01-01
