Pete Pete - 4 years ago 191
Swift Question

stringByReplacingCharactersInRange does not work?

I am attempting to replace a character with another one. For some reason stringByReplacingCharactersInRange does not work. I have not found a simple explanation on how to resolve this issue.

var binaryColor: String = "000"
(binaryColor as NSString).stringByReplacingCharactersInRange(NSMakeRange(0, 1), withString: "1")
println("This is binaryColor0: \(binaryColor)")

The result is 000 and not 100.
Thanks for any help!

Answer Source

You don't need to cast it to NSString to use stringByReplacingCharactersInRange you just need to change the way you create your string range as follow:

update: Xcode 7.2 • Swift 2.1.1

let binaryColor = "000"
let resultString = binaryColor.stringByReplacingCharactersInRange(
    Range(start: binaryColor.startIndex, end: binaryColor.startIndex.advancedBy(1))
    , withString: "1")
print("This is binaryColor: \(resultString)")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download