How to encode and decode a nested array using Codable and PropertyListEncoder?

I have a UICollectionView with multiple sections. Thus my data source for the collection view is a nested array of type [[DayData?]]. There is an instance of DayData for every cell and each inside array corresponds with each section. In DayData.swift, DayData has one property, a String and conforms to Codable. The problem I am struggling with is how to properly encode and decode this nested array.

static func saveToFile(days: [[DayData?]]) {     let propertyListEncoder = PropertyListEncoder()     let encodedDays = try? propertyListEncoder.encode(days)     try? encodedDays?.write(to: archiveURL,     options: .noFileProtection) }  static func loadFromFile() -> [[DayData?]]? {     let propertyListDecoder = PropertyListDecoder()     if let retrievedDayData = try? Data(contentsOf: archiveURL),         let decodedDays = try?           propertyListDecoder.decode(Array<Array<DayData>>.self, from:           retrievedDayData) {         return decodedDays     }     return nil } 

Right now I call saveToFile(days:) after the String property of an element DayData in the nested array is reassigned like this:

dayDataArray[indexPath!.section][indexPath!.item]?.moodColor =

When I call loadFromFile(), it returns nil, so my data isn’t saving. The program builds successfully.

I would really appreciate any help. I’m new to iOS and Swift, so I apologize if this is a dumb question.

EDIT: The loadFromFile() method is throwing this error: "Expected to decode Dictionary<String, Any> but found a string/data instead." I’m guessing this means that the data is decoding into a String rather than a nested array of DayData objects, but I’m not sure why it’s doing this or how to fix it.

EDIT: I made DayData not optional, and it works now.

Add Comment
0 Answer(s)

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.