Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to swap two characters in String Swift4?

Tags:

string

ios

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.

like image 961
Kumar Reddy Avatar asked Dec 26 '17 17:12

Kumar Reddy


1 Answers

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
like image 127
Sulthan Avatar answered Oct 23 '22 13:10

Sulthan