let playground: String = "Hello, playground" let start: String.Index = playground.startIndex let end: String.Index = playground.index(start, offsetBy: 4) let range: ClosedRange<String.Index> = start...end var firstFive: String.SubSequence = playground[range]
Page 75, text extracted from below Figure 7.2:
You will find that firstFive is what is called a “slice” of the original String contained by the playground constant. A slice represents some subcomponent of the original sequence.
Since firstFive is a slice of playground, it is a substring carved out of the original “Hello, playground” String. Slicing a substring from an existing String does not create a new instance of that type. This is efficient, because it means that firstFive does not need its own storage. It shares its storage with playground.
Here I made some assumptions that made me a little bit confused.
Since firstFive is an exact subcomponent of the original sequence playground then in this particular example I’m assuming that both these variables must be two references that point to the same instance, is that right? However, if I modify firstFive by changing its text:
firstFive = "Greetings, Big Nerd Ranch Forums!🤠"
firstFive is now a completely different sequence, it’s no longer an exact subcomponent of playground so my assumption of two references pointing at the same instance doesn’t make sense to me here. At this point, how is firstFive sharing its storage with playground? And why firstFive is still declared as String.SubSequence if you option-click it, shouldn’t it be stored as a new String instance?