既然你明确要求Swift,我已经翻译了链接问题中的顶部asnwer.
let notAllowedCharacters = " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_."; func textField( textField: UITextField,shouldChangeCharactersInRange range: NSRange,replacementString string: String) -> Bool { let set = NSCharacterSet(charactersInString: notAllowedCharacters); let inverted = set.invertedSet; let filtered = string .componentsSeparatedByCharactersInSet(inverted) .joinWithSeparator(""); return filtered != string; }