在 Swift 中使用 stringByReplacingCharactersInRange [英] Using stringByReplacingCharactersInRange in Swift
问题描述
我正在尝试在 Swift/Xcode6 中使用 UITextFieldDelegate 并且我正在努力解决我应该使用 stringByReplaceCharactersInRange 的方式.编译器错误是无法将表达式的类型字符串"转换为$T8"类型.
I'm trying to use UITextFieldDelegate in Swift/Xcode6 and I'm struggling with the way I'm supposed to use stringByReplacingCharactersInRange. The compiler error is 'Cannot convert the expression's type 'String' to type '$T8'.
func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool
{
let s = textField.text.stringByReplacingCharactersInRange(range:range, withString:string)
if countElements(s) > 0 {
} else {
}
return true
}
Xcode 6 Beta 5 更新:问题是 shouldChangeCharactersInRange 给出了一个 NSRange 对象,而我们需要一个 Swift Range 对象来表示 stringByReplaceCharactersInRange.这是否仍然可以被视为错误,因为我不明白为什么我们仍然应该处理 NS* 对象?委托方法的 String 参数无论如何都是 Swift 类型.
Update for Xcode 6 Beta 5: The thing is shouldChangeCharactersInRange gives an NSRange object and we'd need a Swift Range object for stringByReplacingCharactersInRange. Can this still be considered a bug as I don't see why we should still be dealing with NS* objects? The String argument of the delegate method is anyway of a Swift type.
推荐答案
这里介绍了如何在各种 Swift 版本中计算结果字符串.
Here's how to calculate the resulting string in various Swift versions.
请注意,所有方法都以完全相同的方式使用 -[NSString stringByReplacingOccurrencesOfString:withString:]
,只是语法不同.
Note that all methods use -[NSString stringByReplacingOccurrencesOfString:withString:]
in exactly the same way, just differing in syntax.
这是计算结果字符串的首选方法.转换为 Swift Range
并在 Swift String
上使用它很容易出错.例如,在对非 ASCII 字符串进行操作时,Johan 的答案在几个方面是不正确的.
This is the preferred way to calculate the resulting string. Converting to a Swift Range
and use that on a Swift String
is error prone. Johan's answer for example is incorrect in a couple of ways when operating on non-ASCII strings.
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`
}
斯威夫特 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)
这篇关于在 Swift 中使用 stringByReplacingCharactersInRange的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!