Skip to content

Latest commit

 

History

History
18 lines (13 loc) · 1.6 KB

File metadata and controls

18 lines (13 loc) · 1.6 KB

When you get a substring from a string, the result is an instance of the Substring class rather than the String class. It has most of the same methods as String, but should only be used for a short period of time. To store the result for a longer time, you should to convert your substring back into a String:

let greeting = "Hello, world!"
let index = greeting.index(of: ",") ?? greeting.endIndex
let beginning = greeting[..<index]
// beginning is "Hello"
 
// Convert the result to a String for long-term storage.
let newString = String(beginning)

The reason for this behaviour is that, as a performance optimization, a substring can reuse parts of the memory being used to store the original string, or another substring. This means you don't have to pay for copying a String until you modify it. However, this reuse also means that the entire original String must be kept in memory for as long as any of its Substrings are in use. Hence why Substrings aren't suitable for long term storage.

String Substring memory usage

Previous Note | Back To Contents | Next Note