How to merge Array of Structure in Swift

Viewed 145
struct Message {
    var id: Int
    let referenceNumber : String
    let transactionNumber : String
    let transactionDate : String
}

struct Amount: Identifiable {
    var id: Int
    let value: Int
    let date: String
    var message = [Message]()
    }

let messages : [Message] = [
    .init(id: 0, referenceNumber: "RXX123", transactionNumber: "TXX123", transactionDate: "Jan/12/2021"),
    .init(id: 1, referenceNumber: "RXX124", transactionNumber: "TXX124", transactionDate: "Feb/12/2021"),
    .init(id: 2, referenceNumber: "RXX125", transactionNumber: "TXX125", transactionDate: "Jan/12/2021")
]

var amounts: [Amount] = [
    .init(id: 0, value: 1000,date: "Jan/12/2021"),
    .init(id: 1, value: 2000,date: "Feb/12/2021"),
    .init(id: 2, value: 3000,date: "Jan/12/2021")
]

How can I club both Arrays of Structure with identifier 'id' to form a working Dictionary so that it can be used into various views of the IOS app when someone taps on the Amount and it takes them to the next view which shows the relevant Message reference of TxnDate,RefNo etc.

I am Using it Xcode project to make a presentation app

struct FrontView: View {
    init(){
        UITableView.appearance().backgroundColor = .clear
        UITableViewCell.appearance().backgroundColor = .clear
    }
    @State private var selections: String? = nil
    
    let messages : [Message] = [
    .init(id: 0, referenceNumber: "RXX123", transactionNumber: "TXX123", transactionDate: "Jan/12/2021"),
    .init(id: 1, referenceNumber: "RXX124", transactionNumber: "TXX124", transactionDate: "Feb/12/2021"),
    .init(id: 2, referenceNumber: "RXX125", transactionNumber: "TXX125", transactionDate: "Jan/12/2021")
]
    
    var amounts: [Amount] = [
    .init(id: 0, value: 1000,date: "Jan/12/2021"),
    .init(id: 1, value: 2000,date: "Feb/12/2021"),
    .init(id: 2, value: 3000,date: "Jan/12/2021")
]
    var body: some View{
        NavigationView{
            VStack(alignment: .center){
                List{
                    ForEach(amounts){amount in
                        
                        NavigationLink(
                        destination: Text(amount.message),//not working
                        tag: "",
                        selection: $selections) {UserRow(user: amount)}
                    }
                }.background(DiamondBackground().edgesIgnoringSafeArea(.all))
                
                
            }
            
        }
        .navigationBarTitle(Text("Dynamic List"))
    }
}
1 Answers

I would suggest creating a dictionary, and appending by Id a tuple which contains both objects, it will look as the following:

typealias MessageAmount = (Message,Amount)
var dict = [String:MessageAmount]
for (index,message) in messages.enumerated() {
    dict[message.id] = (message,amounts[index])
}
Related