Contents of Swift dictionaries and arrays being lost

Just when I think I am finally starting to understand Swift I come across a gotcha like the following:

I have two object, a swiftui display and one of data to be displayed. Ok, sounds easy.

The data is read out of a JSON file so I have a set of arrays and dictionaries. The data is valid when read, it is definitely there, but when I go to display it, its gone. Just vanished. Wasted about a day on this so far, and I’ve seen it before, the inability to pass out of an object an array or dictionary with contents intact.

If I create an array var, and not let the system do it, contents are preserved. So, in the data object I’ll have something like this:

struct DataObject{
	var item: [String:Any]

	item=JSONData serialized out of memory, and may have say, 12 fields
}

In my SwiftUI module I have:

var item=dataObject.item

dataObject.item now has 0 fields.

I can allocate and initialize a dictionary in DataObject and those elements come through fine. So it seems like the stuff being serialized from JSON is being deleted out from under me.

Have you tried this: (not actual code, but close enough)

struct DataObject {
    var items: [String : Any]
}

// In some other function somewhere, where you get the JSON data:
func getData() -> DataObject {
    var jsonData = // get your JSON data
    var jsonDataAsItems = // convert to items, if needed
    return DataObject(items: jsonDataAsItems)
}

// Somewhere else:
var myItems: DataObject = getData()

I've used the struct to say, "this is what the data object looks like," but it's not holding the data itself.

The getData() function creates an instance of the struct and returns it.

You use the result of that function in another variable - myItems, which should contain the JSON data, as required.

What if you try with computed var ?

struct DataObject{ var item: [String:Any] { JSONData serialized out of memory, and may have say, 12 fields } }

I ended up having to map the data into a new dictionary that miraculously stayed intact when floated up to the SwiftUI layer.

Maddening beyond belief.

Combined with a Switfui gotcha I wasted about 8 hours doing something that would have taken me 15 minutes in UIKit and ObjC.

Contents of Swift dictionaries and arrays being lost
 
 
Q