how to select select and use the properties of the instance of the struct selected

So far, and with help from this forum, I have an app that that lets the user create a favorites list of Drugs. Drug is a struct. I can add and delete instances of the struct. But my question is, how do i select one favorite, and how can i acces the properties of the struct selected import SwiftUI

struct Drug: Identifiable, Codable {
  var id = UUID()
  var name: String
  var amount: String
  var unitamount : String
  var bag: String
  
 var isRead: Bool = false
}





 class Favoritos: ObservableObject {
 @Published var favs = [Drug]() {
   didSet {
     if let encoded = try? JSONEncoder().encode(favs) {
       UserDefaults.standard.set(encoded, forKey: "Favs")
     }
   }
 }
   init() {
     if let savedItems = UserDefaults.standard.data(forKey: "Favs") {
       if let decodedItems = try? JSONDecoder().decode([Drug].self, from: savedItems) {
        favs = decodedItems
         return
       }
     }

     favs = []
   }
}

struct FavListView: View {
  @StateObject var favoritos = Favoritos()
//  @State var newdrug = Drug(name: "", amount: "", bag: "")
  @State private var showingAddView = false
  func removeItems(at offsets: IndexSet) {
    favoritos.favs.remove(atOffsets: offsets)
  }
  var body: some View {
     
    NavigationView {
      VStack{
//        List {
//          TextField ("Droga", text: $newdrug.name)
//          TextField ("Cantidad", text: $newdrug.amount)
//          TextField ("Volumen", text: $newdrug.bag)
//        }
         
        List
        { ForEach(favoritos.favs) { drug in
          Text("\(drug.name) \(drug.amount) \(drug.unitamount) en \(drug.bag)")
           
        }.onDelete(perform: removeItems)
           
        }.navigationTitle("Infusiones favoritas")
          .navigationBarTitleDisplayMode(.inline)
          .accentColor(.black)
         
        Button ("agregar nuevo favorito") {showingAddView = true }
       
//        Button ("Add") {
//        favoritos.favs.insert(Drug(name: newdrug.name, amount: newdrug.amount, bag: newdrug.bag), at: 0)
//
//
//                }
         
      }.sheet(isPresented: $showingAddView) {
        AddView(favoritos: favoritos)
       
    }
    }
     
  }
     
    struct FavListView_Previews: PreviewProvider {
      static var previews: some View {
        FavListView()
      }
    }
  }

import SwiftUI

struct AddView: View {   @ObservedObject var favoritos : Favoritos   @State var newdrug = Drug(name: "", amount: "", unitamount: "", bag: "")       var body: some View {     VStack{       List {         TextField ("Droga", text: $newdrug.name)           .disableAutocorrection(/@START_MENU_TOKEN@/true/@END_MENU_TOKEN@/)         TextField ("Cantidad", text: $newdrug.amount)         TextField ("Unidad", text: $newdrug.unitamount)           .autocapitalization(/@START_MENU_TOKEN@/.none/@END_MENU_TOKEN@/)         TextField ("Volumen", text: $newdrug.bag)       }                                }                       Button ("Add") {         favoritos.favs.insert(Drug(name: newdrug.name, amount: newdrug.amount, unitamount: newdrug.unitamount, bag: newdrug.bag), at: 0)                                  }             }   }

struct AddView_Previews: PreviewProvider {   static var previews: some View {     AddView(favoritos : Favoritos())   } }

You did not format all code with code formatter, it is really hard to understand.

how do i select one favorite, and how can i acces the properties of the struct selected

When you select in a list, you select a String: see here: https://www.hackingwithswift.com/quick-start/swiftui/how-to-allow-row-selection-in-a-list

Change

  var body: some View {
     
    NavigationView {
      VStack{
        List
        { ForEach(favoritos.favs) { drug in
          Text("\(drug.name) \(drug.amount) \(drug.unitamount) en \(drug.bag)")
        }

To

    @State private var selection: String?

    var body: some View {
        NavigationView {
            List(favoritos.favs, id: \.self, selection: $selection) { drug in
          Text("\(drug.name) \(drug.amount) \(drug.unitamount) en \(drug.bag)")
            }

So to find which it is, you have to find which corresponds to the String.

What you get is the String defined here

          "\(drug.name) \(drug.amount) \(drug.unitamount) en \(drug.bag)"

So, you could

  • parse this String to find the first word => drugName
  • filter favoritos.favs
let selected = favoritos.favs.filter { $0.name.contains(drugName) }

Then you access selected properties: selected.bag for instance.

Thanks Claude31 Below is the whole code of the two views I have so far I tried your suggestion but i didn't get what i need, so i commented it out when i changed the code i couldn't select any row My objective is to be able to create instances of the DRUG struct in addView that are added to my favorites list in favView, I managed that so far. My next goal is to be able to select a row from my favorite list and be able to use that specific instance of the struct in another place

import SwiftUI

struct Drug: Identifiable, Codable, Hashable {
  var id = UUID()
  var name: String
  var amount: String
  var unitamount : String
  var bag: String
  
 var isRead: Bool = false
}





 class Favoritos: ObservableObject {
 @Published var favs = [Drug]() {
   didSet {
     if let encoded = try? JSONEncoder().encode(favs) {
       UserDefaults.standard.set(encoded, forKey: "Favs")
     }
   }
 }
   init() {
     if let savedItems = UserDefaults.standard.data(forKey: "Favs") {
       if let decodedItems = try? JSONDecoder().decode([Drug].self, from: savedItems) {
        favs = decodedItems
         return
       }
     }

     favs = []
   }
}

struct FavListView: View {
  @StateObject var favoritos = Favoritos()
//  @State var newdrug = Drug(name: "", amount: "", bag: "")
  @State private var showingAddView = false
  func removeItems(at offsets: IndexSet) {
    favoritos.favs.remove(atOffsets: offsets)
  }
  @State private var selection: String?

  var body: some View {
     
    NavigationView {
      VStack{
//        List {
//          TextField ("Droga", text: $newdrug.name)
//          TextField ("Cantidad", text: $newdrug.amount)
//          TextField ("Volumen", text: $newdrug.bag)
//        }
    
//        List(favoritos.favs, id: \.self, selection: $selection) { drug in
//             Text("\(drug.name) \(drug.amount) \(drug.unitamount) en \(drug.bag)")
//              }
//        .toolbar {
//          EditButton()
//        }
         
        List
        { ForEach(favoritos.favs) { drug in
          Text("\(drug.name) \(drug.amount) \(drug.unitamount) en \(drug.bag)")

        }.onDelete(perform: removeItems)

        }.navigationTitle("Infusiones favoritas")
          .navigationBarTitleDisplayMode(.inline)
          .accentColor(.black)

          .toolbar {
            EditButton()
          }
         
        Button ("agregar nuevo favorito") {showingAddView = true }
       
//        Button ("Add") {
//        favoritos.favs.insert(Drug(name: newdrug.name, amount: newdrug.amount, bag: newdrug.bag), at: 0)
//
//
//                }
         
      }.sheet(isPresented: $showingAddView) {
        AddView(favoritos: favoritos)
       
    }
    }
     
  }
     
    struct FavListView_Previews: PreviewProvider {
      static var previews: some View {
        FavListView()
      }
    }
  }
import SwiftUI

struct AddView: View {
  @ObservedObject var favoritos : Favoritos
  @State var newdrug = Drug(name: "", amount: "", unitamount: "", bag: "")
   
  var body: some View {
    VStack{
      List {
        TextField ("Droga", text: $newdrug.name)
          .disableAutocorrection(/*@START_MENU_TOKEN@*/true/*@END_MENU_TOKEN@*/)
        TextField ("Cantidad", text: $newdrug.amount)
        TextField ("Unidad", text: $newdrug.unitamount)
          .autocapitalization(/*@START_MENU_TOKEN@*/.none/*@END_MENU_TOKEN@*/)
        TextField ("Volumen", text: $newdrug.bag)
      }
       
      
         
      }
       
       
      Button ("Add") {
        favoritos.favs.insert(Drug(name: newdrug.name, amount: newdrug.amount, unitamount: newdrug.unitamount, bag: newdrug.bag), at: 0)
         
        
              }
       
    }
  }


struct AddView_Previews: PreviewProvider {
  static var previews: some View {
    AddView(favoritos : Favoritos())
  }
}

Any Help? I dont understand why i cant select a row

how to select select and use the properties of the instance of the struct selected
 
 
Q