字典追加不在Swift

时间:2017-06-13 15:39:56

标签: swift dictionary append

为什么append(data)无效?

import Foundation

//This is working.
let tablelist:[String: String] = [
    "red1": "manu1",
    "blue1": "chelsea1",
    "yellow1": "dort1",
    "green1": "nakamura1",
    "purple1": "real1"
]

var resulttablelist = [String: String]()

resulttablelist = tablelist

resulttablelist.removeAll()

for data in tablelist {
if data.value.contains("manu1") {

    //This append(data) not working. I have an error. I need your help.
    var resulttablelist = [String: String]()
    resulttablelist.append(data)

    print(resulttablelist)
    }
}

错误:

//Error!! value of type '[String : String]' has no member 'append' 

此示例代码正在运行。

for data in tablelist {
if data.value.contains("manu1") {
    print(data)
    }
}

将打印:

(key: "red1", value: "manu1")

5 个答案:

答案 0 :(得分:1)

Dictionary在Swift中没有append方法。您需要使用<?xml version="1.0" encoding="utf-8"?> <result> <message> <to>plus</to> <from>A</from> </message> <message> <to>plus</to> <from>B</from> </message> <message> <to>minus</to> <from>C</from> </message> <message> <to>minus</to> <from>D</from> </message> ... ... ... </result> 代替resulttablelist["manu1"] = data

答案 1 :(得分:0)

尝试resulttablelist [Key] = Value

resulttablelist是一个字典,所以它需要有一个键值对

其中键和值都是字符串

编辑:在你的情况下它将是

  resulttablelist[data.key] = data.value

答案 2 :(得分:0)

您无法附加密钥及其附加值,您应该替换附加的附加条件 resulttablelist[data.key] = data.value 每次重置数组时,请注意for中的行var resulttablelist = [String: String]()

答案 3 :(得分:0)

您也可以使用此方法:

YOUR_DICTIONARY.updateValue(_ value: Dictionary.Value, forKey key: Dictionary.Key)

来源:

https://developer.apple.com/documentation/swift/dictionary/1539001-updatevalue

答案 4 :(得分:-1)

将此var resulttablelist = String:字符串排除在brakets

之外
  import Foundation

    //This is working.
    let tablelist:[String: String] = [
                                      "red1": "manu1",
                                      "blue1": "chelsea1",
                                      "yellow1": "dort1",
                                      "green1": "nakamura1",
                                      "purple1": "real1"
                                      ]

    var resulttablelist = [String: String]()

    resulttablelist = tablelist

    resulttablelist.removeAll()

    var newresulttablelist = [String: String]()
    for data in tablelist {
        if data.value.contains("manu1") {

            newresulttablelist.append(data)

            print(newresulttablelist)
        }
    }