出于某种原因,这给了我一个错误。
swearWordPair
被定义为[String]
。例如
["Hello", "Hi"]
let swearWordsAndReplacements : [[String]] = [["anus", "butt"], ["arse", "butt"]]
这给我的错误是
Cannot invoke 'stringByReplacingOccurrencesOfString' with an argument list of type '(String, withString: String, options: NSStringCompareOptions, range: NSRange)
然而,我查找了这个函数的参数,似乎我的所有参数都是正确的。这是一个快速的错误吗?
var string = insult
for swearWordPair in swearWordsAndReplacements {
string = string.stringByReplacingOccurrencesOfString(swearWordPair[0],
withString: swearWordPair[1],
options: NSStringCompareOptions.CaseInsensitiveSearch,
range: NSMakeRange(0, count(string)))
}
答案 0 :(得分:3)
Range
不是NSRange
,而是Swift
范围。在这种情况下,您可以传递nil
来代表整个String
:
string = string.stringByReplacingOccurrencesOfString(swearWordPair[0],
withString: swearWordPair[1],
options: .CaseInsensitiveSearch,
range: nil)
如果您想限制范围,可以像这样创建Range<String.Index>
:
var string = "I laid my head at the head of the bed"
// Only replace within the first 15 characters
let myrange = string.startIndex ..< advance(string.startIndex, 15)
string = string.stringByReplacingOccurrencesOfString("head",
withString: "blanket",
options: .CaseInsensitiveSearch,
range: myrange)
println(string)
输出:
我把毯子放在床头