Swift: How do I use String.Index to work with replaceSubrange

Solution 1:

The index type of String is not Int-compatible because a character can contain multiple bytes.

A workaround to convert Int indices to String.Index is NSRange which matches the startPos and length parameters and which can be reliably converted to Range<String.Index>.

By the way to modify the string inside the function and never use it makes no sense. A better way is an inout parameter

func MID(destin: inout String, startPos: Int, length: Int, source: String )
{
    let nsRange = NSRange(location: startPos, length: length)
    guard let range = Range(nsRange, in: destin) else { return }
    destin.replaceSubrange(range, with: source)
}