Home > other >  SwiftUI - sorting a list containing strings and doubles
SwiftUI - sorting a list containing strings and doubles

Time:11-25

Goal: in a SwiftUI list containing strings and doubles, sort it by the doubles.

The code bellow works, but it sorts by strings.

Question, how can I sort it by doubles?

Obs: changing sorteByValue to [Double : String] is not an option because of how I am fetching the data.

Any help is super appreciated! : )

import SwiftUI

struct ContentView: View {
    
    @State private var sorteByValue: [String : Double] = ["key1": 0, "key2": 0]

    var body: some View {
        
        List {
              ForEach(sorteByValue.sorted(by: >), id: \.value) { key, value in
                  HStack{
                    Text("\(value, specifier: "%.2f")")
                    Text(key)
                  }
              }
          }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

CodePudding user response:

Approach:

  • Use sorted(by:), it takes a closure with 2 parameters element1 and element2.
  • If you can tell the function how to sort 2 elements then it can sort the array

Solution:

sorteByValue.sorted(by: { lhs, rhs in lhs.value < rhs.value })

Reference:

https://developer.apple.com/documentation/swift/keyvaluepairs/sorted(by:)

  • Related