Conforming to Comparable, what am I missing? [Solved]

Hello, I'm no doubt being very stupid, and hopefully just writing this post will make me see where I've gone wrong, but I'd appreciate any help.

I have a simple struct which I would like to make conform to Comparable.

Here's the code, but Xcode complains that the type doesn't conform. It offers a fixit to add the stub function which would allow conformation, but it's exactly the same signature as the existing function....

What am I missing?
Thanks

		struct DayMonthPair: Hashable, Comparable {

			var day: Int
			var month: Int

			static func < (lhs: DayMonthPair, rhs: DayMonthPair) -> Bool {
				if (lhs.month == rhs.month) {
					return lhs.day < rhs.day
				}
				//	In this case the months are not the same, so compare on that
				return lhs.month < rhs.month
			}

			static func == (lhs: DayMonthPair, rhs: DayMonthPair) -> Bool {
				return (lhs.month == rhs.month) && (lhs.day == rhs.day)
			}
			
		}

Can't reproduce. Your code works fine exactly as-is when I paste it into a Playground.

Yes, I've just done exactly the same thing... hmmm...

In my Xcode project the struct is defined within a function - is that allowed?

Here's the code from the playground that now fails to compile with the same error:

import UIKit


func doAThing() {
	
	struct DayMonthPair: Hashable, Comparable {
		
		var day: Int
		var month: Int
		
		static func < (lhs: DayMonthPair, rhs: DayMonthPair) -> Bool {
			if (lhs.month == rhs.month) {
				return lhs.day < rhs.day
			}
			//	In this case the months are not the same, so compare on that
			return lhs.month < rhs.month
		}
		
		static func == (lhs: DayMonthPair, rhs: DayMonthPair) -> Bool {
			return (lhs.month == rhs.month) && (lhs.day == rhs.day)
		}
		
	}
	
	print("Doing a Thing...")

	let nov11 = DayMonthPair(day: 11, month: 11)
	let jan02 = DayMonthPair(day: 02, month: 01)

	if nov11 > jan02 {
		print("November is indeed after Jan")
	}

	
}


doAThing()

See if your code compiles in the latest nightly toolchains; that's a longstanding bug that was fixed in June:

3 Likes

Not an answer to your actual problem, but note that you can simplify the code a bit by comparing tuples:

static func < (lhs: DayMonthPair, rhs: DayMonthPair) -> Bool {
    (lhs.month, lhs.day) < (rhs.month, rhs.day)
}

static func == (lhs: DayMonthPair, rhs: DayMonthPair) -> Bool {
    (lhs.month, lhs.day) == (rhs.month, rhs.day)
}
2 Likes

Ah! Thanks very much. The error appears to go away with yesterday's nightly toolchain. I get another error about not being able to use a package because it was compiled with a different version of the compiler, but I assume that's not hiding the other error.

Wow, 2016, that bug has been around a while...

Thanks again and thanks @Martin for the tip.