11

I want to check if a string contains only numerals. I came across this answer written in Objective-C.

NSRange range = [myTextField.text rangeOfCharacterFromSet:[NSCharacterSet letterCharacterSet]];
if(range.location == NSNotFound) {
    // then it is numeric only
}

I tried converting it to Swift.

let range: NSRange = username.rangeOfCharacterFromSet(NSCharacterSet.letterCharacterSet())

The first error I came across is when I assigned the type NSRange.

Cannot convert the expression's type 'Range?' to type 'NSRange'

So I removed the NSRange and the error went away. Then in the if statement,

let range = username.rangeOfCharacterFromSet(NSCharacterSet.letterCharacterSet())
if range.location == NSNotFound {

}

I came across the other error.

'Range?' does not have a member named 'location'

Mind you the variable username is of type String not NSString. So I guess Swift uses its new Range type instead of NSRange.

The problem I have no idea how to use this new type to accomplish this. I didn't come across any documentation for it either.

Can anyone please help me out to convert this code to Swift?

Thank you.

Community
  • 1
  • 1
Isuru
  • 30,617
  • 60
  • 187
  • 303

1 Answers1

23

This is an example how you can use it:

if let range = username.rangeOfCharacterFromSet(NSCharacterSet.letterCharacterSet()) {
    println("start index: \(range.startIndex), end index: \(range.endIndex)")
}
else {
    println("no data")
}
Greg
  • 25,317
  • 6
  • 53
  • 62
  • 2
    Is there way to compare it with `NSNotFound`? If I do this `let range = username.rangeOfCharacterFromSet(NSCharacterSet.letterCharacterSet()) == NSNotFound` I get this error, **'Int' is not convertible to 'Range'** – Isuru Aug 11 '14 at 10:59
  • The else statement (no data) is equivalent with no found. – Greg Aug 11 '14 at 11:01
  • Yes i found a solution for this i am using this work for validate a string for that i am using this code var isValid = true let name = self.TrimText(nameText) as NSString let nameSet = NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ- ") let set = nameSet.invertedSet let range = name.rangeOfCharacterFromSet(set) let isInvalidName = range.location != NSNotFound if(isInvalidName){ isValid = false } – Ali Raza Oct 21 '14 at 05:27
  • ^ I think he missed the point, you don't need `range.location` in Swift (nor `NSNotFound`. The `else` clause above alone, means it was not found. – Martin Marconcini Feb 23 '16 at 21:58