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

SOLVED: Day 9 Closure Question - captainFirstSorted

Forums > 100 Days of SwiftUI

Hi there,

Chugging along and have come to a screeching hault while I learn closures.

The team sorting by captain has given me a headache.

In this example:

let team = ["Gloria", "Suzzane", "Piper", "TIffany", "Tasha"]
let sortedTeam = team.sorted()
print (sortedTeam)

func captainFirstSorted(name1: String, name2: String) -> Bool {
    if name1 == "Suzzane"{
        return true
    } else if name2 == "Suzzane" {
        return false
    }

    return name1 < name2
}

let captainFirstTeam = team.sorted(by: captainFirstSorted)
print(captainFirstTeam)

How does the captainfirstSorted function know that name1 and name2 are first and second values of the array team?

I assume it just plucks out the first and second values of the array but I don't understand how this works as I would expect comparing each name to a position in the array (team[x]) as shown below:

func captainFirstSorted() -> Bool {
    if team[0] == "Suzzane"{
        return true
    } else if team[1] == "Suzzane" {
        return false
    }

    return team[0] < team[1]
}

Thank you for any help you can provide!! :)

2      

@rooster gives a great explanation. See -> Closure Sorting

I gave it a shot here. See -> Obelix tries to explain the Captain Sort

Keep coding! And, please keep asking questions.

3      

Thank you! Those posts did the trick.

Appreciate the encouragement.

-e

2      

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.