stringByReplacingCharactersInRange does not work?

自古美人都是妖i 提交于 2020-01-06 18:31:32

问题


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!


回答1:


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

Or simply

let resultString2 = binaryColor.stringByReplacingCharactersInRange(
    binaryColor.startIndex..<binaryColor.startIndex.advancedBy(1),
    withString: "1")



回答2:


You have to set the variable:

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


来源:https://stackoverflow.com/questions/30671680/stringbyreplacingcharactersinrange-does-not-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!