The final word on NSStrings: Mutable and Immutable

后端 未结 6 623
忘掉有多难
忘掉有多难 2020-12-16 23:14

I\'ve read in several books... and online... about immutable and mutable strings. They claim \"immutable strings\" can\'t be changed. (But they never define \"change\".)

6条回答
  •  既然无缘
    2020-12-17 00:20

    An immutable string (or indeed, any immutable object) is one that can't be changed at all after initialisation.

    Here's the advantage of using immutable strings, in (pseudo-)pseudo-code:

    // if using mutable strings
    let a = "Hello World";
    let b = a;
    a.replace("Hello", "Goodbye");
    

    Now what does a hold? "Hello World"? "Goodbye World"? Now what does b hold?

    If strings are mutable, then it might hold "Goodbye World". This may be what you want. It might not be.

    With immutability, it becomes very clear that b still points to the original string, because the replace method can't have changed the actual string, but rather returned a reference to a new string.

    You might not see much benefit in this example. But if a and b are referenced and used in different parts of the code, or in different threads, having immutable references removes a lot of potential errors.

提交回复
热议问题