1

I need to print String inside the String extensions. I am aware the addition of one String with another String. But,

Why below code give me an error?

Is it possible to solve this error with this way?

If yes, How?

Code:

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

    }
}

Error :

Cannot use mutating member on immutable value of type 'String'

Rajamohan S
  • 7,229
  • 5
  • 36
  • 54

2 Answers2

12

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.

Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • returning is better than assigning to self. +1. – Alexander Aug 02 '17 at 03:59
  • First Solution : I think `var string = "Hello" ` is poor when I need to print 1000 of separate fruits. Also it gives me an error ` Cannot assign value of type '()' to type 'String?'` and the Second one is good. Thanks for the brief explanation – Rajamohan S Aug 02 '17 at 04:38
1

parent is a mutating method, and since fruit calls it, fruit is mutating as well, and must be declared as such.

Alexander
  • 59,041
  • 12
  • 98
  • 151
  • 1
    If I make `mutating func fruit()` also I get error `cannot use mutating member on immutable value of type 'String'`. Can you please elaborate with example? – Rajamohan S Aug 02 '17 at 04:40