The truth is quite strange the handling of chains in Swift. However, a StackOverflow response in English has helped me much. The general idea is the following (for version 3 of the language):
var cadena = "<font size=\"2\""
let inicio = cadena.index(cadena.endIndex, offsetBy: -2)
Chains have two indexes, initially called startIndex
and end called endIndex
. From them, we can build intermediate indexes using the methods index
To obtain the index where the number starts in your chain, we obtain the final index and we subtract 2 from it, this we do using the parameter offsetBy
that can be positive (which means that we move "to the right" ) or negative (towards "the left")
let fin = cadena.endIndex
let rango = inicio..<fin
We create a range using the operator ..<
, which results in a unique range. The ...
operator can also be used for an inclusive one
cadena.replacingCharacters(in: rango, with: "nuevo")
which returns: "<font size="nuevo"
The complete code looks like this:
import Foundation
var cadena = "<font size=\"2\""
let inicio = cadena.index(cadena.endIndex, offsetBy: -2)
let fin = cadena.endIndex
let rango = inicio..<fin
cadena.replacingCharacters(in: rango, with: "nuevo")