zztop
zztop

Reputation: 781

Extension to Test if NSString is Numeric in Swift

One can test if a String is numeric in swift using:

extension String  {
    var isNumber: Bool {
        return !isEmpty && rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil
    }
}

Is there a similar way to check if an NSString is numeric? I have played around with the above but can't get anything to compile.

Upvotes: 1

Views: 992

Answers (3)

Mohamed Obaya
Mohamed Obaya

Reputation: 2593

You can create a function in an extension

extension NSString  {
func isNumber() -> Bool {
    let str: String = self as String
    return Int(str) != nil || Double(str) != nil
    }
}
let x: NSString = "32"
x.isNumber() // true

Upvotes: 1

bpolat
bpolat

Reputation: 3908

According to Apple's documentation :

A string is a series of characters, such as "Swift", that forms a collection. Strings in Swift are Unicode correct and locale insensitive, and are designed to be efficient. The String type bridges with the Objective-C class NSString and offers interoperability with C functions that works with strings.

So you can just type cast and use same method.

Upvotes: 0

Leo Dabus
Leo Dabus

Reputation: 236360

You would need to check if the length is greater than 0 and if the range location is equal to NSNotFound:

extension NSString  {
    var isNumber: Bool {
        return length > 0 && rangeOfCharacter(from: CharacterSet.decimalDigits.inverted).location == NSNotFound
    }
}

("1" as NSString).isNumber  // true

("a" as NSString).isNumber // false

Upvotes: 4

Related Questions