How can you use the "ctype.h" library in Swift to be able to use isAlpha
or isSpace
on characters? Or is there a better, Swift, way of doing it?
This question is answered, but it doesn't seem to work: Swift: how to find out if letter is Alphanumeric or Digit
It doesn't specify how to import the library. Could someone point me in the right direction?
Here's what I've got so far:
extension String {
subscript (i : Int) -> String {
return String(Array(self)[i])
}
}
let whitespace = NSCharacterSet.whitespaceCharacterSet()
let phrase = "Test case"
for var i=0; i<countElements(phrase); i++ {
if whitespace.characterIsMember(phrase[i]) { //error
println("char is whitespace")
}
}
Use NSCharacter on the entire string,not character-by-character:
Output:
I created a String extension that does exactly this, hope it's useful.
This answer works with text fields. I was going crazy trying to search for whitespace on a UItextfield without searching the string content of it. This works for UItextfields:
Swift 4:
This is for a regular string, also in swift 4
Shorter extension (swift 4.1)
You can change the
.whitespacesAndNewlines
with any otherCharacterSet
like this: