如何在swift 3中检查对象是否是字典?

时间:2017-03-23 10:23:13

标签: swift dictionary

试过'是'关键字。

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

这会出错,说"''总是如此"。 我只想检查对象是否是字典。它可以与任何键对任何值对。

enter image description here

密钥是可清除的,并且不接受Any关键字。

5 个答案:

答案 0 :(得分:8)

如果你想首先检查一个任意对象是否是一个字典,你必须使该对象不被指定:

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

现在您可以检查对象是否是字典

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

但这种方式是理论上的,仅用于学习目的。基本上,将一个不同的类型强加给一个非常愚蠢的类型。

答案 1 :(得分:4)

如果你只是想检查你的对象是否是Dictionary,你可以这样做:

if let dictionary = yourObject as? Dictionary{

    print("It is a Dictionary")

}

答案 2 :(得分:1)

把它放在操场上:

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字典数组具有特定类型

答案 3 :(得分:1)

我更喜欢在解析if let个对象时使用guard letJSON

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

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

答案 4 :(得分:0)

只需使用is运算符检查类型一致性。

这里有一个小片段,我会检查它是Dictionary还是Array

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

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

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