Search code examples
iostextviewswift3

Does UITextView have a String which stores all words as text?


Does a UITextView have just one String which contains all words as a text? I am curious about an idea which I came up with. Can I do something to words added into the UITextView? Like am I able to detect offensive words or bad words by making an array?

If I have an array called myArray. Inside this array, for example, 'badword1', 'badword2', and 'badword3' are stored. If words of these are inputed.

My thought was in the following;

  1. create a UITextView called myTextView and set over a UIViewController, and then connect myTextView.
  2. Create an array called myArray. Inside this array, prohibited words are stored.
  3. maybe....by using a for-loop, like

    for words in myArray {
        if myTextView.contains(words) { 
            print("words are found")
        }
    }
    

    I do not think this code works, but it is my guess.

Thanks.


Solution

  • Create an extension for String

    extension String{
        func contains(_ text: String, substring: String) -> Bool {
    
    
            return text.range(of: substring, options: NSString.CompareOptions.literal) != nil
        }
    }
    

    Then you can do this-

    for words in myArray {
    if myTextView.text.contains(words) { 
        print("words are found")
    }
    }