将字典附加到Swift数组

时间:2015-05-20 06:09:28

标签: ios arrays swift dictionary

我有这个Swift代码,其中我试图将Dictionary附加到数组。

        var savedFiles: [Dictionary<String, AnyObject>] = []
        var newEntry =  Dictionary<String,AnyObject>()

        if let audio = receivedAudio?.filePathURL {
            newEntry["url"] = audio
        }
        newEntry["name"] = caption

        savedFiles.append(newEntry! as Dictionary<String,AnyObject>)

这在最后一行(附加)Cannot invoke 'append' with an argument list of type '(Dictionary<String, AnyObject>)'

中给出了错误

有什么想法吗?我也试过去掉力展开。

5 个答案:

答案 0 :(得分:1)

请试试这个:

var savedFiles: [[String: AnyObject]] = []
var newEntry: [String: AnyObject] = [:]

if let audio = receivedAudio?.filePathURL {
    newEntry["url"] = audio
}
newEntry["name"] = caption

savedFiles.append(newEntry)

答案 1 :(得分:1)

你刚刚在游乐场尝试了它的工作,只有你应该知道:音频可以随时为零,在这种情况下,这个键值对不会被添加到newEntryDictionary中。

RandomAccessFile

答案 2 :(得分:0)

绝对没问题:

var savedFiles: [Dictionary<String, AnyObject>] = []
var newEntry =  Dictionary<String, AnyObject>()
newEntry["key"] = "value"
savedFiles.append(newEntry)

虽然这是“Swifty”-Style:

var savedFiles = [[String: AnyObject]]()
var newEntry = [String: AnyObject]()
newEntry["key"] = "value"
savedFiles.append(newEntry)

我正在使用Xcode 7.2.1。

答案 3 :(得分:0)

Swift 4 开始,使用词典的正确方法是:

声明空字典(关联数组):

namesOfIntegers[16] = "sixteen"

附加到字典:

let key = 16
if namesOfIntegers.keys.contains(key) {
  // Does contain array key (will print 16)
  print(namesOfIntegers[key])
}

检查字典是否包含密钥:

{{1}}

直接来自Apple:https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html

答案 4 :(得分:-1)

var savedFilesDictionary = [String: AnyObject]()
var newEntryDictionary = [String: AnyObject]()

if let audio = receivedAudio?.filePathURL {
     newEntryDictionary["url"] = audio
}
newEntryDictionary["name"] = caption

savedFilesDictionary.append(newEntryDictionary)

试试这个。