Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 780
abhimuralidharan Avatar asked Mar 23 '17 10:03

abhimuralidharan


People also ask

How do you check if a value is in a dictionary Swift?

To check if a specific key is present in a Swift dictionary, check if the corresponding value is nil or not. If myDictionary[key] != nil returns true, the key is present in this dictionary, else the key is not there.

How can I check if an object is of a given type in Swift?

Use the type check operator ( is ) to check whether an instance is of a certain subclass type. The type check operator returns true if the instance is of that subclass type and false if it's not.

How do you check if key already exists in dictionary Swift?

contains() Return Values The contains() method returns: true - if the dictionary contains the specified key or value. false - if the dictionary doesn't contain the specified key or value.

Is Swift dictionary ordered?

There is no order. Dictionaries in Swift are an unordered collection type. The order in which the values will be returned cannot be determined. If you need an ordered collection of values, I recommend using an array.


2 Answers

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

But this way is theoretical and only for learning purposes. Basically it's pretty silly to cast up a distinct to an unspecified type.

like image 85
vadian Avatar answered Sep 28 '22 10:09

vadian


If you just want to check if your object is Dictionary you can just do this:

if let dictionary = yourObject as? Dictionary{

    print("It is a Dictionary")

}
like image 34
Aaqib Hussain Avatar answered Sep 28 '22 08:09

Aaqib Hussain