iosarraysswiftnsdictionarytypecase

Trying to saveArray, got error - Cannot convert value of type '[Data]' to expected argument type '[Dictionary<String, AnyObject>]'


I'm trying to save array added from tableview using this function:

class func saveArray(_ value: [Dictionary<String, AnyObject>], key: String) {
        let data = NSKeyedArchiver.archivedData(withRootObject: value)
        UserDefaults.standard.set(data, forKey: key)
    }

Below is the function where I want to save the array:

func addItemCat(items: [Data]) {
        print("ITEM: ", items)
        dataSource.myListTableViewController.myListArr = items
        self.myListTV.isHidden = false
        UserDefaultsHelper.saveArray(items, key: Constants.myList.myList)
    }

However, I got this error: Cannot convert value of type '[Data]' to expected argument type '[Dictionary String, AnyObject ]'

Below is my Data model: data model screencap

I'm new to Swift and I hope someone can explain what is the problem.


Solution

  • Problem is with data types, saveArray function expects value parameter of type array of dictionary [Dictionary<String, AnyObject>], but you are passing array of data model objects which is a type-mismatch error.

    To solve this:

    First, You should not use pre-defined keywords for creating your custom object. Use DataObject instead:

    struct DataObject {
    
    }
    

    Now change your saveArray function as:

    class func saveArray(_ value: [DataObject], key: String) {
        let data = NSKeyedArchiver.archivedData(withRootObject: value)
        UserDefaults.standard.set(data, forKey: key)
    }
    

    and addItemCat, function as:

    func addItemCat(items: [DataObject]) {
        print("ITEM: ", items)
        dataSource.myListTableViewController.myListArr = items
        self.myListTV.isHidden = false
        UserDefaultsHelper.saveArray(items, key: Constants.myList.myList)
    }