Reputation: 89
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.
Upvotes: 0
Views: 9799
Reputation: 1367
As of Swift 4, the correct way to work with dictionaries:
var namesOfIntegers = [Int: String]()
namesOfIntegers[16] = "sixteen"
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
Upvotes: 1
Reputation: 2024
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)
Upvotes: 1
Reputation: 9845
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.
Upvotes: 0
Reputation:
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)
Upvotes: 1
Reputation: 6893
var savedFilesDictionary = [String: AnyObject]()
var newEntryDictionary = [String: AnyObject]()
if let audio = receivedAudio?.filePathURL {
newEntryDictionary["url"] = audio
}
newEntryDictionary["name"] = caption
savedFilesDictionary.append(newEntryDictionary)
Try this.
Upvotes: -1