Why can't my code find the numbers in my line?

I want to check if my string contains ONLY digits. To do this, I try:

if resultTitles[indexPath.row].rangeOfCharacterFromSet(badCharacters) == nil { let badCharacters = NSCharacterSet.decimalDigitCharacterSet().invertedSet print("Index: \(indexPath.row)") } 

It worked, but now it is not. This is really weird. What is wrong here?

+1
ios swift
source share
2 answers

Does an error appear in the if statement line or the next line? The error is probably related to the badCharacters declaration after , which you use in the if statement, and because it allows you not to mutate it if it already exists.

0
source share

try the following:

 if resultTitles[indexPath.row].rangeOfCharacter(from: NSCharacterSet.decimalDigits.inverted) == nil { print("Index: \(indexPath.row)") } 

An alternative solution is to check if a string contains only numbers:

  CharacterSet.decimalDigits.isSuperset(of: CharacterSet(charactersIn: yourString)) 
-one
source share

All Articles