Search code examples
iosstringswift4

How to swap two characters in String Swift4?


in Swift4, the String is Collections. You will no longer use characters property on a string.

func swapCharacters(input:String,index1:Int,index2:Int)-> String { // logic to swap }

let input = "ABCDEFGH"

If I call the function with (input,3,8) then the output should be

Output : ABCHEFGD

Note: In Swift4, Strings are collections.


Solution

  • Fairly straightforward since String is a collection:

    func swapCharacters(input: String, index1: Int, index2: Int) -> String {
        var characters = Array(input)
        characters.swapAt(index1, index2)
    
        return String(characters)
    }
    
    let input = "ABCDEFGH"
    print(swapCharacters(input: input, index1: 3, index2: 7)) //ABCHEFGD
    

    or, to provide a direct array-like operation:

    extension String {
        mutating func swapAt(_ index1: Int, _ index2: Int) {
            var characters = Array(self)
            characters.swapAt(index1, index2)
            self = String(characters)
        }
    }
    
    var input = "ABCDEFGH"
    input.swapAt(3, 7)
    print(input) //ABCHEFGD