wasimsandhu wasimsandhu - 1 year ago 147
Swift Question

swift - using replaceRange() to change certain occurrences in a string

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"

will change every "a" in that string to an "e", returning:


I am trying to get the index of the first "a" and then replacing it using
, 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
, but I feel like I've got this whole method wrong. Help?


This is is what you want to do:

var animal = "elaphant"
if let range = animal.rangeOfString("a") {
  animal.replaceRange(range, with: "e")

rangeOfString will search for the first occurrence of the provided substring and if that substring can be found it will return a optional range otherwise it will return nil.

we need to unwrap the optional and the safest way is with an if let statement so we assign our range to the constant range.

The replaceRange will do as it suggests, in this case we need animal to be a var.