skyguy skyguy - 6 months ago 54
iOS Question

Swift: how to censor/filter text entered for swear words, etc?

I just want to see whether there is an established way to do this, or how one would go about this.

I have a text field that essentially acts as a form in my iOs app where a user can post something. I can't have users posting swear words/inappropriate crap, so I want to filter out and display an error if the string they enter contains one of these words.

How do other apps in Swift do this? Do they just search through the string to see if it contains the word (obviously not within other words, but standing alone) or is there another method?

How can I accurately filter out the swear words from my user post in Swift?


Construct a list of words you consider to be swear words, and simply check the user entered string whether any of these words are contained within the string.

E.g. (Swift 3)

import Foundation

func containsSwearWord(text: String, swearWords: [String]) -> Bool {
    return swearWords.reduce(false) { $0 || text.contains($1) }

// example usage
let listOfSwearWords = ["darn", "crap", "newb"]
let userEnteredText1 = "This darn didelo thread is a no no."
let userEnteredText2 = "This fine didelo thread is a go."
print(containsSwearWord(text: userEnteredText1, swearWords: listOfSwearWords)) // true
print(containsSwearWord(text: userEnteredText2, swearWords: listOfSwearWords)) // false

I'll include a Swift 2.2 version later (currently not on my mac), but until then, you can tweak the above using e.g. the answers in the following thread