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.
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.
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: ?
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 ( [] ).
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.
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")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With