如何优雅地比较 Swift 中的元组?

How to elegantly compare tuples in Swift?(如何优雅地比较 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 中的元组?

基础教程推荐