String.replacingCharacters(in: RangeExpression with: StringProtocol) errors in Swift 4.2

In Swift 4.2 I'd expect the following code to change "tetrisX" to "TetrisX"


let range = 0..<1
"testrisX".replacingCharacters(in: range, with: "T")


but it fails to compile with the following error:

generic parameter 'T' could not be inferred


the method signature came from the autocomplete in Xcode 10.


Here's the documentation for the method:

https://developer.apple.com/documentation/foundation/nsstring/1410029-replacingcharacters

Its signature uses NSRange instead of Range and String instead of StringProtocol.


let range = NSMakeRange(0, 1)
"testrisX".replacingCharacters(in: range, with: "T")


However, the following code also gives an error:

argument type 'NSRange' (aka '_NSRange') does not conform to expected type 'RangeExpression'

"testrisX".replacingCharacters(in: range, with: "T")

Accepted Answer

When you want to use `replacingCharacters(in:with:)` for String (not NSString), the `range` passed to `in` parameter needs to be a range of String.Index.


You may need to write something like this:

let str = "testrisX"
let range = str.startIndex..<str.index(after: str.startIndex)
print(str.replacingCharacters(in: range, with: "T")) //->TestrisX


And the right documentation page for this method is:

replacingCharacters(in:with:)

String.replacingCharacters(in: RangeExpression with: StringProtocol) errors in Swift 4.2
 
 
Q