-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.

3
  • 2
    Possible duplicate of how to save and read array of array in NSUserdefaults in swift? Commented Oct 18, 2017 at 7:35
  • I’m asking about array of array, the link you posted is about dictionary, even though the title said array of array Commented Oct 18, 2017 at 7:39
  • Why don't you show what a sample 2d array that you are talking about looks like so that they will no misunderstanding? Commented Oct 18, 2017 at 9:14

1 Answer 1

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")

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.