UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: For loop in sorting function just plain does not work...

Forums > Swift

The sort should order skippers by how many first places, then how many second places etc. It uses an array of counts of places for each skipper where places[n] is how many time they scored nth place

I presume this should work, but based on the debug printouts below the code there are times when the if statement just seems to evaluate incorrectly? Code snippet - ignore the commented code (that version of sort worked fine):

static func < (lhs:Skipper, rhs:Skipper) -> Bool {
        var result = false
//        if lhs.regattaNet < rhs.regattaNet {
//            result = true
//        } else {
//            result = comparePlaces(first: lhs, second: rhs)
        for race in 1...lhs.places.count-1 {
            if lhs.places[race] > rhs.places[race] {
                result = true
            }
            print(lhs.sailNum, lhs.places[race], rhs.sailNum, rhs.places[race], result)
        }

Here is one part of the printout that seems to be failing: 171 0 250 0 false 171 0 250 0 false 171 0 250 0 false 171 0 250 0 false 171 0 250 0 false 171 1 250 1 false 171 1 250 1 false 171 1 250 1 false 171 1 250 2 false <--- 171 2 250 2 false 171 2 250 2 false 171 2 250 2 false

2      

Note for the future: Put your print results from the console in code tags too; makes it easier to read.

171 0 250 0 false 
171 0 250 0 false 
171 0 250 0 false 
171 0 250 0 false 
171 0 250 0 false 
171 1 250 1 false 
171 1 250 1 false 
171 1 250 1 false 
171 1 250 2 false <--- 
171 2 250 2 false 
171 2 250 2 false 
171 2 250 2 false

That's the correct result for the code you have. lhs.places[n] has a score of 1; rhs.places[n] has a score of 2 (since you didn't include race in your print statement, I don't know the actual index into places being used here). Per your code:

var result = false
if lhs.places[race] > rhs.places[race] { //i.e., if 1 > 2
    result = true
}

Since 1 is not greater than 2, the result is false.

3      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.