abhi1992 abhi1992 -4 years ago 207
Swift Question

How to check if an object is dictionary or not in swift 3?

Tried the 'is' keyword.

// Initialize the dictionary

let dict = ["name":"John", "surname":"Doe"]

// Check if 'dict' is a Dictionary

if dict is Dictionary {
print("Yes, it's a Dictionary")
}


This will give an error saying "'is' is always true".
I just want to check if an object is a dictionary. It can be with any key any value pairs.

enter image description here

The key is hashable and it is not accepting the Any keyword.

Answer Source

If you want to check if an arbitrary object is a dictionary first of all you have to make the object unspecified:

let dict : Any = ["name":"John", "surname":"Doe"]

Now you can check if the object is a dictionary

if dict is Dictionary<AnyHashable,Any> {
    print("Yes, it's a Dictionary")
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download