Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 222
Isuru Avatar asked Aug 11 '14 10:08

Isuru


People also ask

What is the range of a string?

Returns a range of consecutive characters from string, starting with the character whose index is first and ending with the character whose index is last. An index of 0 refers to the first character of the string. first and last may be specified as for the index method.

How do you find the range of a string in a string Swift?

Ranges and Strings We can demonstrate this by working with a NSRange and a NSString that contains an emoji: let emojiText: NSString = "? launcher" print(emojiText. substring(with: NSRange(location: 0, length: 2))) // Expected: ?

Can you index a string in Python?

String Indexing In Python, strings are ordered sequences of character data, and thus can be indexed in this way. Individual characters in a string can be accessed by specifying the string name followed by a number in square brackets ( [] ).

Can you index a string in Java?

You can get the character at a particular index within a string by invoking the charAt() accessor method. The index of the first character is 0, while the index of the last character is length()-1 . For example, the following code gets the character at index 9 in a string: String anotherPalindrome = "Niagara.


1 Answers

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")
}
like image 125
Greg Avatar answered Oct 04 '22 19:10

Greg