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 中的元组?
基础教程推荐
- Android:对话框关闭而不调用关闭 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01