rfrittelli
rfrittelli

Reputation: 1211

Number class swift

Is there a way to easily determine whether a value is a number? I was looking through the swift standard lib and couldn't seem to come to any conclusion. Something like so:

    var val: Any = ...
    if let number = val as? Number {
        //do something
    }

I don't really need to cast it just figure out whether or not it's a number. Rather than doing a bunch of Int,Double,etc checks.

Upvotes: 2

Views: 733

Answers (1)

Antonio
Antonio

Reputation: 72760

Given a variable of Any type, you can check if it's a number using a function like this:

func isNumber(value: Any) -> Bool {
    return (value is Int) || (value is UInt) || (value is Float) || (value is Double)
}

Interesting case, if the variable is of AnyObject type, any of these:

value is Int
value is UInt
value is Float
value is Double
value is Bool

will return true for all these data types:

  • Int
  • UInt
  • Float
  • Double
  • Bool

so for example:

let x: AnyObject = false
x is Int // <== evaluates to true
x is Float // <== evaluates to true

Upvotes: 2

Related Questions