How to swap two letters in a sentence in swift 4

sentence.text: thank you
inputA.text: 2
inputB.text :7

ouput will be : tyank hou

so user input "2" and inputs "3" and inputs "thank you".
so, the 2nd and 3rd letters would swap and become "tyank hou"

Not sure what you mean and if your example still contains typos, did you mean something like this?

"thank you".capitalized == "Thank you"

sorry it will become: tyank hou

so user input "2" and inputs "3" and inputs "thank you".
so, the 2nd and 3rd letters would swap and become "tyank hou"

Okay got you, have fun:

extension String {
  mutating func swap(at index: String.Index, to character: Character) {
    let endIndex = self.index(after: index)
    let range = index ..< endIndex
    assert(indices.contains(index) && indices.contains(endIndex))
    replaceSubrange(range, with: String(character))
  }
}

var string = "thank you"

var index = string.index(string.startIndex, offsetBy: 1)
string.swap(at: index, to: "1") // "t1ank you"
index = string.index(string.startIndex, offsetBy: 6)
string.swap(at: index, to: "2") // "t1ank 2ou"
var s: [Character] = "thank you".map { $0 }
s.swapAt(2-1, 7-1) // -1 because indexing is zero-based
print(String(s)) // prints tyank hou
1 Like

instead of "2" string.swap(at: index, to: "2") // "t1ank 2ou"

example:
var input2 = inputB.text
var input1 = inputA.text

how can I add 'input2' instead of "1":

and input1 instead of "2"

I hope you got the idea how to finish the rest ;)

var string = "thank you"

let i = string.index(after: string.startIndex)
let j = string.index(after: i)

string.replaceSubrange(i ..< j, with: "WHATEVER") // "tWHATEVERank you"