How swift string is internally managing memory ?

When i create a intance of swift String :

Let str = String ("Hello")

As swift String are immutable, and when we mutate the value of these like:

str = "Hello world ......." // 200 characters 

Swift should internally allocate new memory and copy the content to that buffer for update .

But when i checked the addresses of original and modified str, both are same?

Can you help me understand how this allocation and mutation working internally in swift String?

Answered by DTS Engineer in 815197022

How did have you “checked the addresses”? If you’re coming from a C-based language, be aware that & doesn’t mean what you might think it means. See The Peril of the Ampersand.

Beyond that, a String is not an object but a struct. It uses a variety of clever techniques — most notably inline storage and copy-on-write — to optimise its performance.

These are all implementation details, mind you. They have changed in the past and it’s not hard to imagine them changing again in the future. If you want your code to work reliably, you have to access String via its API.

Still, if you’re curious about the implementation, the Swift team has talked about this publicly and, of course, the implementation is open source. A good place to start is UTF-8 String post on the Swift blog.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

How did have you “checked the addresses”? If you’re coming from a C-based language, be aware that & doesn’t mean what you might think it means. See The Peril of the Ampersand.

Beyond that, a String is not an object but a struct. It uses a variety of clever techniques — most notably inline storage and copy-on-write — to optimise its performance.

These are all implementation details, mind you. They have changed in the past and it’s not hard to imagine them changing again in the future. If you want your code to work reliably, you have to access String via its API.

Still, if you’re curious about the implementation, the Swift team has talked about this publicly and, of course, the implementation is open source. A good place to start is UTF-8 String post on the Swift blog.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

How swift string is internally managing memory ?
 
 
Q