Search code examples
iosswiftuserdefaults

appending value to a data array and saving in Userdefault swift


I am trying to add a value to an array and store in userdefaults but I got error intitialy when trying to append the new value to the value pulled. below is my code.

private func putArray(_ value: GMSAutocompletePrediction?, forKey key: String) {
        guard let value = value else {
            return
        }
        let newArray = getArray(forKey: key)?.append(value) // error here

        storage.setValue(NSKeyedArchiver.archivedData(withRootObject: value), forKey: key)
}

private func getArray(forKey key: String) -> [GMSAutocompletePrediction]? {
        guard let data = storage.data(forKey: key) else { return nil}
        return NSKeyedUnarchiver.unarchiveObject(with: data) as? [GMSAutocompletePrediction]
}

below is my error

Cannot use mutating member on immutable value: function call returns immutable value


Solution

  • The problem is getArray(forKey: key)? is immutable , you can't attach append directly to it , so you need

    var newArray = getArray(forKey: key) ?? []
    newArray.append(value)