Fabian Boulegue
Fabian Boulegue

Reputation: 6608

Swift NSString check for Numbers

I have a Array:NSString that look like

[X1],[Tester],[123],[456],[0]

Now i have to check if a position (always the same) is a number or a string
So i tried

 var test = Array[0].intValue
        print(test) 

but as [0] is a string it should not return 0 as it also could be [4]

0

is there a way to check if a NSString is a number only (return of true/false would be enough)?

full code example

var Array: [NSString] = ["X1","Fabian","100","200","not avaible"]
/* could also be Array:
var Array0: [NSString] = ["X2","Timo","200","300","300"]
*/
//need to check if Array[4] is a number or not so its "text" or "number"

var test = Array[4].intValue
print(test)

//return 0

Upvotes: 0

Views: 537

Answers (2)

Lukas
Lukas

Reputation: 3433

If you wanna collect the indexes where the array elements are numbers, you can use mapping and returning the indexes where the element can be converted to number.

var Array0: [NSString] = ["X1","Fabian","100","200","not avaible"]
var numbersAt: [Int] = Array0.enumerate().map{ (index, number) in
    return (Int(number as String) == nil ? -1 : index)  
}
print("indexes: \(numbersAt)") //numbersAt will have the indexes unless they're not numbers in which case it'll have -1

//Another option will be to filter the array and collect only the number strings 
var numbers = Array0.filter { Int($0 as String) != nil }
print("numbers: \(numbers)")

Upvotes: 0

Mohammed Elrashidy
Mohammed Elrashidy

Reputation: 1871

In swift2: You can use Int(<your variable>) it returns the number if it can cast, else it return nil, and you can check against the returned value.

example using optional condition:

let s = "Some String"
if let _ = Int(s) {
    print("it is a number")
}else{
    print("it is not a number")
}

this example should return "it is not a number"

Upvotes: 4

Related Questions