How to check if an object is a dictionary or not in fast 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 a Dictionary")
}

This will result in an error: “is is always true.” I just want to check if the object is a dictionary. It can be with any key any pairs of values.

enter image description here

The key hashable and does not accept the Any keyword.

+4
source share
5 answers

If you want to check whether an arbitrary object is a dictionary, first of all, you must make the object undefined:

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

But this path is theoretical and for educational purposes only. Basically, it's pretty dumb to distinguish a non-standard type.

+8
source

, "", :

if let dictionary = yourObject as? Dictionary{

    print("It is a Dictionary")

}
+3

:

import UIKit

// Create a dictionary and an array to convert to and from JSON

let d = ["first": "Goodbye", "second": "Hello"]
let a = [1, 2, 3, 4, 5]

let dictData = try! JSONSerialization.data(withJSONObject: d, options: [])
let arrayData = try! JSONSerialization.data(withJSONObject: a, options: [])

// Now that we have set up our test data, lets see what we have

// First, some convenience definitions for the way JSON comes across.

typealias JSON = Any
typealias JSONDictionary = [String: JSON]
typealias JSONArray = [JSON]

// Lets see what we have

let dict = try! JSONSerialization.jsonObject(with: dictData, options: [])
let array = try! JSONSerialization.jsonObject(with: arrayData, options: [])

// testing functions

func isDictionary(_ object: JSON) -> Bool {
    return ((object as? JSONDictionary) != nil) ? true : false
}

func isArray(_ object: JSON) -> Bool {
    return ((object as? JSONArray) != nil) ? true : false
}


// The actual tests

isDictionary(dict) // true
isArray(dict)      // false

isDictionary(array)// false
isArray(array)     // true

JSON

+1

I prefer to use if letor guard letwhen analyzing JSONobjects

if let dict = jsonObject as? [AnyHashable:Any] {
     print("Yes, it a Dictionary")
}

guard let dict = jsonObject as? [AnyHashable:Any] else {
     print("No, it not a Dictionary")
     return
}
+1
source

Just use the operator isto check for type matching.

Here is a small snippet where I check if this is DictionaryorArray

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

if dict is Dictionary<String, String>
{
    print("Yes, it a Dictionary")
}
else
{
    print("No, It other thing")
}

if array is Array<String>
{
    print("Yes, it a Array")
}
else
{
    print("No, It other thing")
}
0
source

Source: https://habr.com/ru/post/1672991/


All Articles