如何在Swift中优雅地比较元组? [英] How to elegantly compare tuples in Swift?
本文介绍了如何在Swift中优雅地比较元组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个不同的类型的元组(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
是这样的函数:
func compareTuples <T:Equatable> (tuple1:(T,T),tuple2:(T,T)) -> Bool{
return (tuple1.0 == tuple2.0) && (tuple1.1 == tuple2.1)
}
我真的不喜欢这个解决方案寻找更优雅的东西。我已经试图写一个扩展,但不能使它工作的元组。
I really dislike this solution and search for something more elegant. I already tried to write an extension but can't make it work for tuples. Do you have a good solution for this problem?
推荐答案
请尝试以下操作:
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中优雅地比较元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文