Get a range from a string
Asked Answered
C

1

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.

Calycle answered 11/8, 2014 at 10:32 Comment(0)
B
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")
}
Bulbar answered 11/8, 2014 at 10:40 Comment(4)
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<String.Index>'Calycle
The else statement (no data) is equivalent with no found.Bulbar
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 }Backwardation
^ 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.Peper

© 2022 - 2024 — McMap. All rights reserved.