Tuesday, November 6, 2018

iOS Swift: Trying to use a mutating function like a function that returns.

You need to understand the difference between a non-mutating function that returns a value, and a void mutating function. The one you wrote, is a mutating function:
mutating func parent(_ word:String){

    self = self+" "+word

}
Mutating functions like this can be used like this:
var string = "Hello"
string.parent("World")
print(string)

As you can see, the call to parent changes the value that is stored in the variable string.
Function that returns is another matter. This is the same parent function, rewritten to return a value:

func parent(_ word: String) -> String {
    return self + " " + word
}

You can use this function that returns like this:

print("Apple".parent("Tree"))
print("Tomato".parent("Plant"))

In this case, nothing is being changed. Values are just being "computed" and returned to the caller.
What you are doing wrong is basically trying to use a mutating function like a function that returns.
To fix this, either change the function to return a value, or use the mutating function properly, as I've showed you.

references:
https://stackoverflow.com/questions/45451133/cannot-use-mutating-member-on-immutable-value-of-type-string/45451230

No comments:

Post a Comment