Search code examples
swiftdictionarygetsetdata-management

How to present a dictionary in a set method swift?


I'm trying to do a set and get method to this Data manager class, from a dictionary and I don't know how to insert the values of the dictionary' in the set and get method (i have changed it from an array to Dic) thanks

class DataManager {

    private static var sharedInstance: DataManager?
    private var recordsArray: [[String:String]] = []

    private let defaults = UserDefaults.standard

    let userRecord: String = "userRecord";

    private init(){}

    public static func getInstance()-> DataManager{
        if DataManager.sharedInstance == nil {
            DataManager.sharedInstance = DataManager()
        }
        return DataManager.sharedInstance!
    }


    //here is my problem - set and get methods
    //I don't know how to move the parameters

    public func setRecordsArray([_:String,path:String])  {
        self.recordsArray.append(?);
        defaults.set(self.recordsArray, forKey: self.userRecord)
    }
    // again the same problem

    public func getRecordsArray() -> [String] {
        let a = self.defaults.array(forKey: self.userRecord);
        return a as! [String];    
    }
}

Solution

  • The key to answering your question is to know the type of variable you want to set and get.

    In this case, the recordsArray variable is an array of dictionaries of string values and keys: [[String:String]]

    So, one way to pass this parameter is to create a variable of the same type as it should be set:

    public func setRecordsArray(array:[[String:String]])  {
            self.recordsArray = array
            defaults.set(self.recordsArray, forKey: self.userRecord)
        }
    

    It simply updates the value of the self.recordsArray variable and sets the value in user defaults.

    The get method works similar, however it returns a variable with the same type that should be returned.

    A ? was added in the return because if there is no saved user defalts, the method returns nil:

    public func getRecordsArray() -> [[String:String]]?{
           if let array = defaults.object(forKey: self.userRecord) as? [[String:String]]{
                self.recordsArray = array
                return array
            }
            return nil
        }
    

    Also, you can make a set method for insert elements inside the array. in this case, parameter type must be like [String:String], the element type of this array:

    public func setRecord(record:[String:String])  {
            if let array = defaults.object(forKey: self.userRecord) as? [[String:String]]{
                self.recordsArray = array
                self.recordsArray.append(record)
                defaults.set(self.recordsArray, forKey: self.userRecord)
            } else{
                self.recordsArray.append(record)
                defaults.set(self.recordsArray, forKey: self.userRecord)
            }
        }