【问题标题】:How to merge Array of Structure in Swift如何在 Swift 中合并结构数组
【发布时间】:2021-08-29 16:31:26
【问题描述】:
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")
]

如何将两个结构数组与标识符“id”结合起来以形成一个工作字典,以便当有人点击 Amount 并将其带到显示的下一个视图时,它可以用于 IOS 应用程序的各种视图TxnDate、RefNo等相关Message参考

我正在使用它 Xcode 项目来制作演示应用程序

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"))
    }
}

【问题讨论】:

    标签: arrays swift struct


    【解决方案1】:

    我建议创建一个字典,并通过 Id 附加一个包含两个对象的元组,它将如下所示:

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

    【讨论】:

      猜你喜欢
      • 2016-05-04
      • 1970-01-01
      • 2021-03-20
      • 1970-01-01
      • 1970-01-01
      • 2018-09-17
      • 1970-01-01
      • 2020-02-01
      • 1970-01-01
      相关资源
      最近更新 更多