不能对'String'类型的不可变值使用变异成员

Raj*_*n S 1 swift swift3

我需要StringString扩展内打印.我知道增加一个String与另一个String.但,

为什么下面的代码会给我一个错误?

用这种方法可以解决这个错误吗?

如果是,怎么样?

码:

extension String{

    func fruit(){
        //After some manipulation with self I need to print
        print("Apple".parent("Tree"))
        print("Tomato".parent("Plant"))


    }

    mutating func parent(_ word:String){

        self = self+" "+word

    }
}
Run Code Online (Sandbox Code Playgroud)

错误:

不能对'String'类型的不可变值使用变异成员

Swe*_*per 12

您需要了解返回值的非变异函数与void变异函数之间的区别.你写的那个是变异函数:

mutating func parent(_ word:String){

    self = self+" "+word

}
Run Code Online (Sandbox Code Playgroud)

像这样的变异函数可以这样使用:

var string = "Hello"
string.parent("World")
print(string)
Run Code Online (Sandbox Code Playgroud)

如您所见,调用parent更改存储在变量中的值string.


返回的功能是另一回事.这是相同的parent函数,重写为返回值:

func parent(_ word: String) -> String {
    return self + " " + word
}
Run Code Online (Sandbox Code Playgroud)

您可以使用此函数返回如下:

print("Apple".parent("Tree"))
print("Tomato".parent("Plant"))
Run Code Online (Sandbox Code Playgroud)

在这种情况下,没有任何改变.值只是被"计算"并返回给调用者.

你做错了什么基本上是试图使用像返回函数一样的变异函数.

要解决此问题,请更改函数以返回值,或者正如我向您展示的那样正确使用变异函数.