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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With