let dict : Any = ["name":"John", "surname":"Doe"]
现在,您可以检查对象是否为字典
if dict is Dictionary<AnyHashable,Any> {
print("Yes, it's a Dictionary")
}
但这种方式只是理论上的,仅用于学习目的。将一个明确的类型转换为未指定的类型基本上是相当愚蠢的。
AnyHashable
的关键字。它很有效。 - abhimuralidharan
if let dictionary = yourObject as? Dictionary{
print("It is a Dictionary")
}
if let
或guard let
。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
}
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字典和数组有特定的类型
[AnyHashable: Any]
。 - Abizern只需使用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")
}
if
语句中检查了它的类型 @abhi1992 - Adolfo
String
(根据JSON规范)。 - vadian