gpt4 book ai didi

swift - 在 Swift 中使用 stringByReplacingCharactersInRange

转载 作者:IT王子 更新时间:2023-10-29 05:13:33 24 4
gpt4 key购买 nike

我正在尝试在 Swift/Xcode6 中使用 UITextFieldDelegate,但我正在努力解决我应该使用 stringByReplacingCharactersInRange 的方式。编译器错误是“无法将表达式的类型‘String’转换为类型‘$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 对象,我们需要一个用于 stringByReplacingCharactersInRange 的 Swift Range 对象。这仍然可以被认为是一个错误吗,因为我不明白为什么我们仍然应该处理 NS* 对象?委托(delegate)方法的 String 参数无论如何都是 Swift 类型。

最佳答案

下面是如何在各种 Swift 版本中计算结果字符串。

请注意,所有方法都以完全相同的方式使用 -[NSString stringByReplacingOccurrencesOfString:withString:],只是语法不同。

这是计算结果字符串的首选方法。转换为 Swift Range 并在 Swift String 上使用它很容易出错。例如,在对非 ASCII 字符串进行操作时,Johan 的回答在几个方面是不正确的。

swift 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)

关于swift - 在 Swift 中使用 stringByReplacingCharactersInRange,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24015848/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com