Are Swift “mutable” strings really mutable, or are they just like Java strings?

前端 未结 6 1430
独厮守ぢ
独厮守ぢ 2020-12-06 05:02

In The Swift Programming Language, in the section on Strings, subsection String Mutability, it says this:

You indicate whether a par

6条回答
  •  一整个雨季
    2020-12-06 05:05

    First, you're using immutable method that makes a new value instance. You need to use mutating methods such as extend to perform the operation in mutating semantic.

    What you did at here is creating a new immutable string and binding it into an existing name.

    var variableString = "Horse"
    variableString += " and carriage"
    

    This is mutating the string in-place without any extra name binding.

    var variableString = "Horse"
    variableString.extend(" and carriage")
    

    Second, purpose of immutable/mutable separation is providing easier and safer programming model. You can make more assumptions safely on immutable data structure, and it can eliminate many headache cases. And this helps optimisation. Without immutable type, you need to copy whole data when you passing it into a function. Otherwise, original data can be mutated by the function, and this kind of effect is unpredictable. Then such functions need to be annotated like "This function does not modify passed-in data.". With immutable type, you can safety assume the function cannot modify the data, then you don't have to copy it. Swift does this implicitly and automatically by default.

    Yes, actually mutable/immutable difference is nothing more than difference in interface in higher level languages like Swift. Value semantic simply means it does not support identity comparison. As many details are abstracted out, internal implementation can be anything. Swift code comment is clarifying the string is using COW tricks, and then I believe both of the immutable/mutable interfaces are actually mapped to mostly-immutable implementations. I believe you will get pretty same result regardless of interface choice. But still, this provides benefits of immutable data type I mentioned.

    Then, the code example, actually does same thing. The only difference is you cannot mutate the original that bound to its name in immutable mode.

提交回复
热议问题