Say I have a string, and I want to change the first "a" in that string to an "e" in order to get the correct spelling.
let animal = "elaphant"
Using stringByReplacingOccurrencesOfString()
will change every "a" in that string to an "e", returning:
elephent
I am trying to get the index of the first "a" and then replacing it using replaceRange()
, like so:
let index = animal.characters.indexOf("a")
let nextIndex = animal.startIndex.distanceTo(index!)
animal = animal.replaceRange(animal.startIndex.advancedBy(nextIndex)..<animal.startIndex.advancedBy(1), with: "e")
However, this code gives me the following error:
Cannot assign value of type '()' to type 'String'
I have been trying to find a way to convert nextIndex into an Int
, but I feel like I've got this whole method wrong. Help?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…