prepend a string to the beginning of another string in swift

To prepend a string to the beginning of another string in Swift, you can use the concatenation operator +. Here's an example:

main.swift
var str1 = "World"
let str2 = "Hello, "

str1 = str2 + str1 // str1 is now "Hello, World"
90 chars
5 lines

Alternatively, you can use the insert(_:at:) method to insert the new string at a specific index. Here's an example:

main.swift
var str1 = "World"
let str2 = "Hello, "

str1.insert(contentsOf: str2, at: str1.startIndex)
// str1 is now "Hello, World"
122 chars
6 lines

You can also get a substring of the original string and then concatenate the two strings together. Here's an example:

main.swift
var str1 = "World"
let str2 = "Hello, "

str1 = str2 + str1.prefix(str1.count) // str1 is now "Hello, World"
109 chars
5 lines

Finally, you can use the append() method to append the contents of the first string to the end of the second string. Here's an example:

main.swift
var str1 = "World"
var str2 = "Hello, "

str2.append(contentsOf: str1) // str2 is now "Hello, World"
101 chars
5 lines

gistlibby LogSnag