0

To replace a string at specific index from

var stringArray:[String] = ["value1", "value2", "value3", "value4"]

We use

stringArray[2] = "new string"

var myNewDictArray = [Dictionary< String, String> ] ()

In my case i have

key/value pair
    ▿ (2 elements)
      - .0: "answer"
      - .1: "0"
  ▿ 1 key/value pair
    ▿ (2 elements)
      - .0: "answer"
      - .1: "0"
  ▿ 1 key/value pair
    ▿ (2 elements)
      - .0: "answer"
      - .1: "0"
  ▿ 1 key/value pair
    ▿ (2 elements)
      - .0: "answer"
      - .1: "0"
  ▿ 1 key/value pair
    ▿ (2 elements)
      - .0: "answer"
      - .1: "0"
  ▿ 1 key/value pair
    ▿ (2 elements)
      - .0: "answer"
      - .1: "0"

In my array

When i try to replace dictionary at specific index say 5, It shows up error:

Swift:: Error: contextual type '[String : String]' cannot be used with array lit eral myNewDictArray[index] = ["answer", "option3"]

Code im using is

for (index, element) in myNewDictArray.enumerated() {

    if(index==5) {

        myNewDictArray[index] = ["answer", "option3"]

    } 

}

I also tried

for (index, element) in myNewDictArray.enumerated() {

    if(index==5) {

        myNewDictArray[index].value(forKey:"answer") = "option3"

    } 

}

Then error is

Swift:: Error: value of type '[String : String]' has no member 'value' myNewDictArray[index].value(forKey:"answer") = "option3"

1

2 Answers 2

3

You probably looking for subscript with your array of dictionary.

var myNewDictArray = [[String:String]]()// OR [Dictionary< String, String>]()
//If you want to update specific key value pair
myNewDictArray[index]["answer"] = "option3"
//If you want to replace whole dictionary with new one
myNewDictArray[index] = ["answer" : "option3"]
Sign up to request clarification or add additional context in comments.

Comments

2

This data structure is not a dictionary. It is an array of dictionaries.

myNewDictArray[index] = ["answer", "option3"]

The above doesn't work because ["answer", "option3"] is an array literal. You are assigning an array to a dictionary. So it of course won't work.

You can make it a dictionary literal by replacing the , with a ::

myNewDictArray[index] = ["answer": "option3"]

But I suggest you to use an array of tuples to store this data:

var myTupleArray = [(String, String)]()

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.