Dershowitz123 Dershowitz123 - 5 months ago 28
iOS Question

Inout parameters in swift 3

This is my code:

func removeFromString( _ s: inout String, Character c:Character) -> Int {
var s1 = s
var nRemoved = 0

while let ix = s1.characters.index(of: c) {
s1.removeSubrange(ix...ix)
nRemoved += 1

}
return nRemoved
}

var s2 = "everest"

let resb = removeFromString(&s2, Character: Character("e"))


My problem is this is supposed to change s2 to "vrst" after using the
inout
parameter
s
. But it's not modifying the
var s2
at all. What wrong I'm I doing? Or I'm expecting a wrong output? Do help. Thanks.

Answer

By moving s into s1 you are making a copy of it since String is a struct, and all structs are pass by value. So in the end you're only changing s1 and not the passed in string, s. Just remove it:

func removeFromString( _ s: inout String, Character c:Character) -> Int {
    var nRemoved = 0

    while let ix = s.characters.index(of: c) {
        s.removeSubrange(ix...ix)
        nRemoved += 1

    }
    return nRemoved
}
Comments