Search code examples
iosswiftrangeios8nsrange

Get a range from a string


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.


Solution

  • 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")
    }