将[string:string]替换为特定索引Swift

时间:2017-03-30 06:55:01

标签: swift

替换特定索引处的字符串
var stringArray:[String] = ["value1", "value2", "value3", "value4"]

我们使用

stringArray[2] = "new string"

var myNewDictArray = [Dictionary<字符串,字符串> ]()

在我的情况下,我有

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"

在我的数组中

当我尝试在特定索引处替换字典时说5, 它显示错误:

  

Swift :: Error:上下文类型'[String:String]'不能用于   阵列点亮           myNewDictArray [index] = [“answer”,“option3”]

使用的代码是

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

    if(index==5) {

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

    } 

}

我也试过

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

    if(index==5) {

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

    } 

}

然后错误

  

Swift :: Error:类型'[String:String]'的值没有成员'value'           myNewDictArray [index] .value(forKey:“answer”)=“option3”

2 个答案:

答案 0 :(得分:2)

此数据结构不是字典。这是一系列词典。

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

上述方法无效,因为["answer", "option3"]是一个数组文字。您正在为字典分配数组。所以它当然不会起作用。

您可以将,替换为:来使其成为字典文字:

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

但我建议你使用一组元组来存储这些数据:

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

答案 1 :(得分:2)

你可能正在用你的字典数组寻找subscript

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