我通常倾向于通过类似于此的调用从Swift中的字符串中删除字符:
textToConvert = inputField.stringValue.stringByReplacingOccurrencesOfString("&", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
现在,输出符合预期。字符串中的所有“&”都将被删除。但是,当我尝试使用2个字符时,例如:
textToConvert = inputField.stringValue.stringByReplacingOccurrencesOfString("HI", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
没有骰子,这两个字符永远不会从字符串中删除。这很奇怪。有谁知道为什么会这样?
编辑:这是整个功能(固定版本):
@IBAction func saySomethingPressed(sender: AnyObject) {
var textToConvert = inputField.stringValue
if (textToConvert == "Hello" || textToConvert == "hello" || textToConvert == "hey"){
responseLabel.stringValue = "Well hello there!"
}
else {
textToConvert = inputField.stringValue.stringByReplacingOccurrencesOfString("HI", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
textToConvert = textToConvert.stringByReplacingOccurrencesOfString("&", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
responseLabel.stringValue = textToConvert
}
}
}
答案 0 :(得分:1)
为了完整性:
textToConvert = inputField.stringValue.stringByReplacingOccurrencesOfString("HI", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
textToConvert = textToConvert.stringByReplacingOccurrencesOfString("&", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
正在重新分配textToConvert变量。