#42: Substrings in Swift 4 or Newer

In modern Swift, string slicing returns a Substring:

let text = "SwiftBites"
let index = text.index(text.startIndex, offsetBy: 5)
let slice = text[..<index]
// Substring("Swift")

Substring shares storage with the original string, which is efficient for short-lived slices.

If you want to store the result long-term or pass it around as a standalone value, convert it back to String:

let prefix = String(slice)

This design avoids unnecessary allocations while keeping slicing fast.

Helpers like prefix(_:) and suffix(_:) follow the same idea and also return Substring values.


I'm also on Twitter and GitHub.

Subscribe via RSS.