TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

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 Superwall.

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn More

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.