-2

I'm trying to save 2d array data using userdefaults, but i'm getting this error Cannot convert value of type '[[String]]' to expected argument type 'String' here is my code

var tempQuestion2 = [tempQuestion]
        if var tempData = UserDefaults.standard.stringArray(forKey: "tempData")
        {
            tempData.append(tempQuestion2)
            tempQuestion2 = tempData
        }
UserDefaults.standard.set(tempQuestion2, forKey: "tempData")

tempQuestion is a string array with data like [“9+1=10”, “5+4=9”] and i want tempQuestion2 to be [["9+1=10, "5+4=9"], ["3+4=7", "4+1=5"]] I'm guessing my issue is at UserDefaults.standard.stringArray. My question is different from the link because that question is about dictionary not array of array.

Daniel.wu
  • 31
  • 1
  • 5
  • 2
    Possible duplicate of [how to save and read array of array in NSUserdefaults in swift?](https://stackoverflow.com/questions/25179668/how-to-save-and-read-array-of-array-in-nsuserdefaults-in-swift) – Hexfire Oct 18 '17 at 07:35
  • I’m asking about array of array, the link you posted is about dictionary, even though the title said array of array – Daniel.wu Oct 18 '17 at 07:39
  • Why don't you show what a sample 2d array that you are talking about looks like so that they will no misunderstanding? – El Tomato Oct 18 '17 at 09:14

1 Answers1

2

There's no problem saving and loading arrays of arrays to UserDefaults, to save your data use:

UserDefaults.standard.set(tempQuestion2, forKey: "tempData")

To read back (and update) the array of arrays use:

// Assuming tempQuestion is [String]
if var tempData = UserDefaults.standard.array(forKey: "tempData") as? [[String]] {
    tempData.append(tempQuestion2)
    UserDefaults.standard.set(tempData, forKey: "temp")

}
idz
  • 12,825
  • 1
  • 29
  • 40