user2586519
user2586519

Reputation: 250

How to append dictionary in array in swift

I have one array of dictionary and I am trying to do is get first object from array and append in my secondArray. Dictionary is [String: AnyObject] and array is of String. Here is my code in didSelectRowAtIndexPath:

let myDictionary: [String: AnyObject] = dataArray[indexPath.row] as! [String : AnyObject]
selectedArray.append(myDictionary)

But I am getting error :

Cannot convert value of type '[String : AnyObject]' to expected argument type 'String'.

How can I add dictionary in array?

Upvotes: 0

Views: 6377

Answers (1)

Nirav D
Nirav D

Reputation: 72410

You need to declare your array of dictionary type [[String: AnyObject]] like this, than append Dictionary inside that array.

var selectedArray = [[String: AnyObject]]()
let myDictionary: [String: AnyObject] = dataArray[indexPath.row] as! [String : AnyObject]
selectedArray.append(myDictionary)

or if you want the array of string [String] then you need to append that specific String from that dictionary like this.

var selectedArray = [String]()
let myDictionary: [String: AnyObject] = dataArray[indexPath.row] as! [String : AnyObject]
if let str = myDictionary["Key"] as? String {
    selectedArray.append(str)
}

Upvotes: 4

Related Questions