4

For example I have a json

var json = JSON(data: data!)

inside it I reference to object

var list = json["OBJECT"]

is there a way, that I can check if it is an object, or array, or string and return bool ?

This doesnt help. var list will always be type of JSON. And I want to find a way to check what is inside.

Community
  • 1
  • 1
Alexey K
  • 6,537
  • 18
  • 60
  • 118
  • 1
    Possible duplicate of [How to determine the type of a variable in Swift](http://stackoverflow.com/questions/24093433/how-to-determine-the-type-of-a-variable-in-swift) – DeyaEldeen Feb 28 '16 at 09:09
  • Explained why it is not duplicate. – Alexey K Feb 28 '16 at 09:12
  • 1
    Most JSON strings received over the network are distinct – at least the collection types they return – so you should "know" rather than "guess". – vadian Feb 28 '16 at 09:39
  • you did have time to comment and edit. i suggest you take a second to pick an answer. – phlebotinum Feb 28 '16 at 10:57

2 Answers2

15

The JSON objects in SwiftyJSON have a type property whose type is an enum

public enum Type: Int {
    case number
    case string
    case bool
    case array
    case dictionary
    case null
    case unknown
}

For example

var list = json["OBJECT"]
switch list.type {
  case .array: print("list is Array")
  case .dictionary: print("list is Dictionary")
  default: break
}
vadian
  • 274,689
  • 30
  • 353
  • 361
0

look at this example:

//let json = ["OBJECT":"stringvalue"]

let testArray = [1,2,3]
let json = ["OBJECT":testArray]

if let element = json["OBJECT"] {
    if element is String {
        print("yes")
    }
    switch element {
    case is String:
        print("is string")
    case is Array<Int>:
        print("is array of int")
    default:
        print("is something else")
    }
}
phlebotinum
  • 1,362
  • 1
  • 14
  • 17