How to traverse through an editable UITextView String to check for certain words in Swift

64 views Asked by At

I have a UITextView that is editable. I am having users type into this, and when they press the submit button, I want to be able to traverse through the string and check for certain words, like Apple, Bug, Dog, etc. If those words are present, I want the submit to cancel, and an alert appear. I just need to know how to check for the words, and then how to cancel the segue.

1

There are 1 answers

1
pbush25 On BEST ANSWER

This is easy to do with the rangeofString method.

var string = "hello Swift"

if string.rangeOfString("Swift") != nil{
   println("exists")
}

Note that this is case sensitive, so if you were looking for "swift" instead of "Swift" you would have to be explicit about that in your function call.

As far as cancelling the segue, the better practice would be to not initialize the segue until after you have done your string validation. This way you know it will only segue if the appropriate string has been entered.

Possible duplicate of question here: How do I check if a string contains another string in Swift?