In Swift, why does slicing a String give you a Substring, and when should you convert it back with String(_:)?
answer
- slices share storage
- cheap now, costly to keep
- different type on purpose
- StringProtocol for both
basics
~20 sSlicing a String returns a Substring that shares the original's storage, so slicing is cheap. Because it keeps that whole storage alive, convert with String(_:) before storing it or passing it to an API that takes String.
solid answer
~40 sOperations such as `prefix(while:)`, `split(separator:)` and range subscripts return `Substring`, a view into the original string's storage that shares its indices, so you can parse without copying. The cost is lifetime: the standard library's documentation warns that a substring holds a reference to the **entire** storage of its base string, even when nothing else references it, which can look like a leak. Swift makes `Substring` a separate type so that the compiler stops you at the boundary: passing one where a `String` is expected fails with "cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'". Convert with `String(_:)`, an O(n) copy of just the slice, when you store the result; make short-lived helpers generic over `StringProtocol` so they accept both.
code
swift · 17 linesstruct ChatRoom {
var authors: [String] = []
mutating func record(author: String) { authors.append(author) }
}
var room = ChatRoom()
let line = "zoë: see you at the café 👋"
let author = line.prefix(while: { $0 != ":" }) // Substring, shares line's storage
// room.record(author: author) // does not compile, see caption
room.record(author: String(author)) // copies just "zoë"
func initials<S: StringProtocol>(_ name: S) -> String {
String(name.prefix(1)).uppercased()
}
print(initials(author), initials("bob")) // Z B
print(author.startIndex == line.startIndex) // true: same index spacego deeper
Recall that prefix, split and range subscripts on a String give you a Substring, and that String(_:) turns it back into a String when an API asks for one.
Explain shared storage and shared indices, quote the compiler error at the type boundary, and show when to convert versus when to accept StringProtocol.
Find substrings stored in models or caches that pin large downloaded texts in memory, and fix them at the storage boundary without copying in hot parsing paths.
Set the convention for parsing code: slices stay local, storage takes String, and read-only helpers are generic over StringProtocol so the rule costs nothing.
## What a Substring is A **`Substring`** is Swift's slice type for strings: `String.SubSequence` is `Substring`. You get one from range subscripts (`text[..<cut]`), from `prefix(_:)`, `suffix(_:)`, `prefix(while:)`, `dropFirst(_:)`, and from each element of `split(separator:)`. It presents the same interface as `String`, so you can count it, iterate it, compare it with `==` and call `uppercased()` on it. What makes it different is storage. The standard library's documentation says a substring **shares its storage with the original string**, which is why slicing is fast: no characters are copied when you take a slice. A substring also shares its base string's **indices**. `author.startIndex` in the example below is equal to `line.startIndex`, not to some fresh zero, and an index found in the substring can be used on the base. ## What a Substring keeps alive Sharing has a price, stated in the `Substring` documentation as an important note: - A substring holds a reference to **the entire storage** of the string it came from, not just the part it presents. - That holds **even when there is no other reference to the original string**. - Storing substrings can therefore **prolong the lifetime** of string data that is otherwise unreachable, which "can appear to be memory leakage". The documentation's advice follows: do not store substrings longer than you need them for a specific operation. The Swift book says the same thing from the other side: substrings are for short-term work, and you convert to `String` for long-term storage. Copy-on-write still applies. Mutating a substring, for example appending to it, gives the substring its own storage; the base string is never changed by edits to a slice. ## Why Swift made it a separate type Swift chose a design the compiler can police. Because `Substring` is a distinct type, the boundary where a short-lived slice would become long-lived storage is visible in the code: ```plaintext error: cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String' ``` That error appears when a `Substring` is passed to a parameter, stored into a property, or appended to an array typed as `String`. It forces a decision at exactly the point where the lifetime question matters. ## Converting, or accepting both There are two honest ways through the type boundary: 1. **Convert with `String(_:)`** when the value is going to live on: stored in a model, put in a dictionary, cached or saved. The initializer copies only the slice; its documented cost is O(n) where n is the length of the substring, and afterwards the big base string can be freed. 2. **Make the function generic over `StringProtocol`** when it only reads the text for a moment: `func initials<S: StringProtocol>(_ name: S) -> String`. Both `String` and `Substring` conform, so callers pass slices without copying. Two things are **not** good reasons to convert: calling a method that `Substring` already has, and comparing with `==`, which works between a `Substring` and a `String`. ## A chat-log example Consider parsing chat lines of the form `zoë: see you at the café`. The parser takes `line.prefix(while: { $0 != ":" })` to get the author. That slice is perfect for checking whether the author is muted or for building initials. Storing it in the room's list of authors is a different matter: every entry would keep its entire source line alive, and when the source is a large downloaded transcript, every stored name keeps the whole transcript alive. `String(author)` copies three characters and lets the transcript go. The same reasoning applies to `split(separator:)`. Splitting a message into words gives an array of `Substring` values, every one of them pointing into the message. Counting the words, filtering out stop words or checking each word against a block list can all stay on the slices. Keeping the words as search keys in a long-lived index is where `map(String.init)` belongs, so that the index owns small strings instead of pinning every original message. ## Rules of thumb - Slice freely inside a function; keep `Substring` as a local, short-lived value. - Convert at the storage boundary: properties, collections, caches and return values that outlive the input. - Prefer `StringProtocol` generics for read-only helpers that should accept both types. - Treat a long-lived `[Substring]` or a `Substring` property as a review flag, unless the base string is known to live just as long anyway.
- Does a Swift Substring start its indices at zero?No. A `Substring` shares its base string's index space, so its `startIndex` is the base string's index where the slice begins. An index found in the slice can subscript the base, and the reverse works inside the slice's bounds. Code that assumes a slice starts at the base's `startIndex`, or rebuilds indices by offsetting from the base, reads the wrong characters.
- Why might a Swift function be declared generic over StringProtocol instead of taking a String?Both `String` and `Substring` conform to `StringProtocol`, so a generic parameter accepts either without forcing the caller to copy. That suits read-only helpers called during parsing, such as validating or formatting a slice. A function that stores its argument should still take `String`, or convert, so the stored value does not hold the caller's whole base string.
- A Substring copies its characters, so it is safe to store anywhere.
- A Substring keeps alive only the characters it presents.
- Mutating a Substring also changes the String it was sliced from.
- Substring indices always start at zero like an Array slice.
- You must convert a Substring to String before comparing it with ==.