inift参数在swift 3中

时间:2016-06-28 15:28:29

标签: ios swift swift3

这是我的代码:

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"))

我的问题是,在使用inout参数s后,应该将s2更改为" vrst" 。但它根本没有修改var s2。我做错了什么?或者我期待错误的输出?帮忙。感谢。

1 个答案:

答案 0 :(得分:18)

通过将s移动到s1,您正在制作它的副本,因为String是一个结构,并且所有结构都是按值传递的。最后,您只需要更改s1而不是传入的字符串s。只需删除它:

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
}