How to elegantly compare tuples in Swift?(如何优雅地比较 Swift 中的元组?)
问题描述
我确实有 2 个不同类型的元组(Double、Double):
I do have 2 different tuples of type (Double, Double):
let tuple1: (Double, Double) = (1, 2)
let tuple2: (Double, Double) = (3, 4)
我想使用一个简单的 if 语句来比较它们的值.比如:
I want to compare their values using a simple if statement. Something like:
if (tuple1 == tuple2) {
// Do stuff
}
这会引发以下错误:
找不到接受提供的=="的重载论据
Could not find an overload for '==' that accepts the supplied arguments
我目前的解决方案是这样的函数:
My current solution is a function like this:
func compareTuples <T: Equatable> (tuple1: (T, T), tuple2: (T, T)) -> Bool {
return (tuple1.0 == tuple2.0) && (tuple1.1 == tuple2.1)
}
我已经尝试编写扩展,但无法使其适用于元组.对于这个问题,你有更优雅的解决方案吗?
I already tried to write an extension but can't make it work for tuples. Do you have a more elegant solution to this problem?
推荐答案
更新
正如 Martin R 在评论中所说,现在可以将包含多达六个组件的元组与 ==
.具有不同组件计数或不同组件类型的元组被认为是不同的类型,因此无法进行比较,但是我在下面描述的简单案例的代码现在已经过时了.
As Martin R states in the comments, tuples with up to six components can now be compared with ==
. Tuples with different component counts or different component types are considered to be different types so these cannot be compared, but the code for the simple case I described below is now obsolete.
试试这个:
func == <T:Equatable> (tuple1:(T,T),tuple2:(T,T)) -> Bool
{
return (tuple1.0 == tuple2.0) && (tuple1.1 == tuple2.1)
}
和你的一模一样,不过我叫它==
.然后是:
It's exactly the same as yours, but I called it ==
. Then things like:
(1, 1) == (1, 1)
是真的并且
(1, 1) == (1, 2)
是假的
这篇关于如何优雅地比较 Swift 中的元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何优雅地比较 Swift 中的元组?


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