How to add a dictionary to an empty array in Swift?

Viewed 35

I'm creating an empty array in swift like this:

var myArray = [String]()

and I create a dictionary like this:

let dict  = ["Deleted":false] as [String : Any]

and I TRY to append the dic to myArray like this:

myArray.append(dict)
    

But the Xcode is complaining with this error:

No exact matches in call to instance method 'append'

I tried to create myArray in a different way like this but this will create other issues in my code as its not String:

myArray: [Dictionary<String,Any>]! = nil

can someone please advice on this?

EDIT:

The suggestions below are correct but I am bumping into another issue here!

To explain this further:

I have a codeable like this:

struct RequestModel: Codable {
    var name: String?
    var newArray = [String]()
    
}

I need to be able to use the myArray value for newArray to send to an API.

But using a dictionary/myArray throws this error:

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

EDIT 2:

This is what I have to send to the API:

{
    "var1": "1",
    "var2": "2",
    
    "newArray": [{"Deleted": false}]
}
1 Answers

I think that you want an array of Dictionaries, so you should declare the variable like

var myArray = [[String:Any]]()
Related