确定`true`是Bool而不是等于1的数字

时间:2016-06-02 16:43:45

标签: swift

标题不是最佳,建议欢迎

Bool和数字值有点麻烦。我想确定AnyObject(来自JSON)是Bool还是数字。

所以我需要一个只有插入的类型真的是Bool或数字才能成功的测试。现在它会自动转换,所有陈述都是真的。

let some : AnyObject = 1

if some is Bool {
    print("is Bool", some as! Bool)
}

if some is Int {
    print("is Int", some as! Int)
}

let some2 : AnyObject = false

if some2 is Bool {
    print("is Bool", some2 as! Bool)
}

if some2 is Int {
    print("is Int", some2 as! Int)
}

let some3 : AnyObject = 1.1

if some3 is Bool {
    print("is Bool", some3 as! Bool)
}

if some3 is Int {
    print("is Int", some3 as! Int)
}

1 个答案:

答案 0 :(得分:1)

11.0true,所有类型都桥接到NSNumber

您可以查看objCType

let some : AnyObject = true

if let type = String.fromCString(some.objCType) {
  switch type {
  case "c" : print("is Bool", some as! Bool)
  case "q" : print("is Int", some as! Int)
  case "d" : print("is Double", some as! Double)
  default :  print("no idea")
  }
} else {
  print("no matching objCType")
}

来源:Type Encodings