This question already has an answer here:
I'm trying to check whether a specific string contains letters or not.
So far I've come across NSCharacterSet.letterCharacterSet()
as a set of letters, but I'm having trouble checking whether a character in that set is in the given string. When I use this code, I get an error stating:
'Character' is not convertible to 'unichar'
For the following code:
for chr in input{
if letterSet.characterIsMember(chr){
return "Woah, chill out!"
}
}
You can use
NSCharacterSet
in the following way :Or you can do this too :
It's up to you, choose a way. I hope this help you.
The trouble with
.characterIsMember
is that it takes aunichar
(a typealias forUInt16
).If you iterate your input using the
utf16
view of the string, it will work:You can also skip the loop and use the
contains
algorithm if you only want to check for presence/non-presence:You should use the
String
s built in range functions withNSCharacterSet
rather than roll your own solution. This will give you a lot more flexibility too (like case insensitive search if you so desire).Substitute
"aeiou"
with whatever letters you're looking for.A less flexible, but fun swift note all the same, is that you can use any of the functions available for
Sequence
s. So you can do this:This of course will only work for individual characters, and is not flexible and not recommended.