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.
The key is hashable and it is not accepting the Any keyword.
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.
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.
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.
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.
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.
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")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With