Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare three values for equality

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.

like image 549
Rappe Stegarn Avatar asked Jun 18 '16 19:06

Rappe Stegarn


2 Answers

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?

like image 168
SeanCAtkinson Avatar answered Sep 27 '22 18:09

SeanCAtkinson


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")
}
like image 31
Ike10 Avatar answered Sep 27 '22 18:09

Ike10