arraysswiftdictionary

Trying to pass array of dictionaries from one view to second view swift


Trying to pass array of dictionaries from view A to second view B in swift.

In view A, using a hidden navigation link in the view to push view B and send arrayMergeT100 to view B

@State var arrayMergeT100 = [[String:Any]]()

NavigationLink(destination:ShowBookChoices(bookOptions: self.$arrayMergeT100),
           isActive: self.$pushActive) {
             EmptyView()
        }.hidden()

View B, trying to access values for key "synopsis" and getting two errors on this line "if let index = bookOptions.index(forKey: "synopsis") {". Error 1- Incorrect argument label in call (have 'forKey:', expected 'where:') and Error 2-Cannot convert value of type 'String' to expected argument type '([String : Any]) throws -> Bool'. Changing forKey: to where: does not make Error2 go away

struct ShowBlindDateChoices: View {
    @Binding public var bookOptions: [[String:Any]]
    var body: some View {
                VStack{
                    if let index = bookOptions.index(forKey: "synopsis")  {
                        let _ = print(bookOptions[index].key, ":", bookOptions[index].value)
                    }

Solution

  • Try this example code to access the keys and values of your construct:

    if let index = bookOptions.firstIndex(where: { $0["synopsis"] != nil })  {
         print(bookOptions[index])
         print(bookOptions[index].keys)
         print(bookOptions[index].values)
     }
    

    Or:

    if let index = bookOptions.firstIndex(where: { $0["synopsis"] != nil }),
        let test = bookOptions[index].first {
        print(test)
        print(test.key)
        print(test.value)
    }