R Menke R Menke - 1 year ago 53
Swift Question

Determine that `true` is a Bool and not a number equal to 1

Title is sub-optimal, suggestions welcome

Ran into a little trouble with

and numeric values. I want to determine if an
(from a JSON) is a
or a number.

So I need a test that will only succeed if the inserted type was truly a
or a number. Now it automatically converts and all statements are true.

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)

Answer Source

1, 1.0, true, all types are bridged to NSNumber

You can check the 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")

Source: Type Encodings