以下是在各种Swift版本中计算结果字符串的方法。
请注意,所有方法的使用
-[NSStringstringByReplacingOccurrencesOfString:withString:]方式完全相同,只是语法不同。
这是计算结果字符串的首选方法。转换为Swift
Range并在Swift上使用它
String容易出错。例如,当对非ASCII字符串进行操作时,Johan的答案在很多方面都是错误的。
斯威夫特3:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let result = (textField.text as NSString?)?.replacingCharacters(in: range, with: string) ?? string // ... do something with `result`}Swift 2.1:
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { let result = (textField.text as NSString?)?.stringByReplacingCharactersInRange(range, withString: string) // ... do something with `result`}Swift 1(仅供参考):
let result = textField.text.bridgeToObjectiveC().stringByReplacingCharactersInRange(range, withString:string)



