-1

Goal: to sort an array of structs per struct.state field.

Current Scenario: Data isn't sorted alphabetically per state.

enter image description here

Here's the code:

struct RevisedNigeriaDataListElement: Identifiable, Equatable {
    let id: UUID
    let state: String
    let cases, active, recovered, deaths: String
}

typealias RevisedNigeriaDataList = [RevisedNigeriaDataListElement]



  func processData(origData: NigeriaDataList) {
        var data: RevisedNigeriaDataList = []

        for item in origData {
            let element = RevisedNigeriaDataListElement(
                id: UUID(),
                state: item.state,
                cases: item.cases.str,
                active: item.active.str,
                recovered: item.recovered.str,
                deaths: item.deaths.str
            )

            data.append(element)
        }
    
        revisedData = data.sorted(by: { $0.state: String, $1.state: String in
            $0 < $1
        })
    }

My problem: is the 'data.sorted'.

enter image description here

Each member of the data struct is a String.
What is the correct syntax?

Frederick C. Lee
  • 9,019
  • 17
  • 64
  • 105
  • you might be interested in sorting a collection using a KeyPath. Check this post https://stackoverflow.com/a/63018749/2303865 – Leo Dabus Apr 29 '21 at 21:07

1 Answers1

4

$0 and $1 are Shorthand Argument Names. The correct syntax is this:

data.sorted(by: { $0.state < $1.state })

Alternatively, you can forgo the shorthand arguments and define them yourself:

data.sorted(by: { firstElement, secondElement in
    firstElement.state < secondElement.state
})

Note that you don't put : String. You are calling the sorted method on an array of RevisedNigeriaDataList, so the type is inferred.

aheze
  • 24,434
  • 8
  • 68
  • 125