ryohei ryohei - 1 month ago 24
Swift Question

How to eliminate an input when there is a space in a String in Swift

I am having trouble right now. I set a custom

TextField
. When users type any word in the box, I want the data to be saved, but I want to set a condition which is every time a word is entered, only one word is allowed in a
String
text. For example, if a user enters a text which is like "Hello", es, I want it to be saved because as it fulfills the condition. However, if it is "hello, world", "hello ", " hello", "I am a super man" or anything like a text with some space in a
String
text, it is not allowed.

for space in text {
if space == " " {
print("Enter only one word please")
return
}
}


This is my attempt to solve this, but it is not working well. I wonder if I should use an array to achive my goal but I have no idea. User inputs should be allowed if there is no space.

Thank you.

Answer

Use this function to check if there are any spaces in your string:

func validate(string: String) -> Bool {
    return string.rangeOfCharacter(from: CharacterSet.whitespaces) == nil
}

Or this one to check if input contains only letters:

func validate(string: String) -> Bool {
    return string.rangeOfCharacter(from: CharacterSet.letters.inverted) == nil
}

An example of how to actually use it:

class ViewController: UIViewController, UITextFieldDelegate {
    //...
    func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool {
        let currentString: NSString = (textField.text ?? "") as NSString
        let newString = currentString.replacingCharacters(in: range, with: string)
        return  validate(string: newString)
    }
}