【问题标题】:SwiftyJSON - is possible to check object type?SwiftyJSON - 可以检查对象类型吗?
【发布时间】:2016-02-28 09:05:32
【问题描述】:

例如我有一个 json

var json = JSON(data: data!)

在其中我引用了对象

var list = json["OBJECT"]

有没有办法,我可以检查它是一个对象、数组还是字符串并返回 bool ?

This 没有帮助。 var list 将始终是 JSON 的类型。我想找到一种方法来检查里面的东西。

【问题讨论】:

  • 解释了为什么不重复。
  • 大多数通过网络接收的 JSON 字符串是不同的——至少它们返回的集合类型是不同的——所以你应该“知道”而不是“猜测”。
  • 您确实有时间发表评论和编辑。我建议你花点时间来选择一个答案。

标签: ios swifty-json


【解决方案1】:

SwiftyJSON 中的 JSON 对象有一个 type 属性,其类型是 enum

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

例如

var list = json["OBJECT"]
switch list.type {
  case .array: print("list is Array")
  case .dictionary: print("list is Dictionary")
  default: break
}

【讨论】:

  • 当我尝试这个时,我得到...... Pattern cannot match values of type 'Type' errors on both case lines
  • @SamLuther 在 Swift 3+ 中,枚举大小写是小写的。我更新了答案。
【解决方案2】:

看看这个例子:

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

【讨论】:

    猜你喜欢
    • 2011-06-29
    • 1970-01-01
    • 1970-01-01
    • 2011-11-10
    • 2011-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-27
    相关资源
    最近更新 更多