Compare three values for equality

随声附和 提交于 2019-12-23 08:17:11

问题


Does anybody know of a shortcut to test whether three numbers are the same? I know this works:

if number1 == number2 && number2 == number3 {

}

But I would like something cleaner, such as;

if number1 == number2 == number3 {

}

It's quite important as I'm comparing a lot of different values.


回答1:


You can use the power of tuples and the Transitive Property of Equality.

if (number1, number2) == (number2, number3) {

}

The clause of this IF is true only when number1 is equals to number2 AND number2 is equals to number3. It means that the 3 values must be equals.




回答2:


You could use a set

if Set([number1, number2, number3]).count == 1 {
    ...

though I'd argue it isn't as transparent as multiple if clauses




回答3:


You can add them in an array and use sets:

var someSet = NSSet(array: [2,2,2])

if someSet.count == 1 {
    print("Same values")
}



回答4:


Don't know of anything other than a Set, I'd suggest wrapping it in a function to make your intent clear. Something along these lines:

func allItemsEqual<T>(items:[T]) -> Bool {
    guard items.count > 1 else { fatalError("Must have at least two objects to check for equality") }
    return Set(items).count == 1
}

func allItemsEqual(items:T...) -> Bool {
    return equal(items)
}

if allItemsEqual(2,3,2) {
    // false
}

if allItemsEqual(2, 2, 2) {
    // true
}

Beyond that, maybe you could get fancy with operator overloading?




回答5:


Try this:

func areEqual<T: NumericType>(numbers: T...) -> Bool {
   let num = numbers[0]
   for number in numbers {
       if number != num {
          return false
       }
   }
   return true
}

Where NumericType is defined in this post: What protocol should be adopted by a Type for a generic function to take any number type as an argument in Swift?

This will allow you to use the function for all number types

You just pass any number of numbers like:

//returns true
if areEqual(1, 1, 1) {
   print("equal")
}


来源:https://stackoverflow.com/questions/37900603/compare-three-values-for-equality

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!