简体   繁体   中英

Appending Dictionary to Swift Array

I have this Swift code in which I'm trying to append a Dictionary to Array.

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

This gives me an error on last line (in append) Cannot invoke 'append' with an argument list of type '(Dictionary<String, AnyObject>)'

Any idea? I also tried remove force unwrapping as well.

Please try this:

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

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

savedFiles.append(newEntry)

Hi just tried on playground its working, only you should know this: audio could be nil any time, in that case this key value pair won't be added in newEntryDictionary.

var savedFilesDictionary = [[String: AnyObject]]()
var newEntryDictionary = [String: AnyObject]()
var receivedAudio = NSURL(string: "/something/some")

if let audio = receivedAudio?.filePathURL {
    newEntryDictionary["url"] = audio
}
newEntryDictionary["name"] = "some caption"
savedFilesDictionary.append(newEntryDictionary)

Absolutely no problem:

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

Although this is the "Swifty"-Style:

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

I am using Xcode 7.2.1.

As of Swift 4 , the correct way to work with dictionaries:

Declare empty dictionary (associative array):

var namesOfIntegers = [Int: String]()

Append to dictionary:

namesOfIntegers[16] = "sixteen"

Check if dictionary contains key:

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

See more, straight from Apple: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html

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

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

savedFilesDictionary.append(newEntryDictionary)

Try this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM