Working with Strings in Swift is quite different then in Objective-C. Inserting a substring into a string is pretty tricky. Let’s assume following task: given is a html string and we want to extend it by adding some style, i.e. we want to add a string of type <style>/**some style*/</style>
before closing tag </head>. Of course, there is a number of ways how to realize it, e.g JavaScript injection, XML manipulation etc. But let’s see how it can be done using Strings’ operations.
Base idea: we split our HTML string into two parts using String[Range<String.Index>]
subscript: before </head> and after </head>. Then we concatenate these parts: part1 + styleString + part2. And this is how it looks in code:
let styleString = String(format: "<style>%@</style>", cssString)
var enrichedHtmlString = htmlString
if let range = enrichedHtmlString.range(of: "</head>") {
let substringPrefix = enrichedHtmlString[enrichedHtmlString.startIndex..<range.lowerBound]
let substringSuffix = enrichedHtmlString[range.lowerBound ..< enrichedHtmlString.endIndex]
enrichedHtmlString = substringPrefix + styleString + substringSuffix
}
Feel free to contact me if you find a better way to realise inserting substrings into strings in Swift.