A slice of a string.
SDK
- Xcode 9.0+
Framework
- Swift Standard Library
Declaration
Overview
When you create a slice of a string, a Substring
instance is the result. Operating on substrings is fast and efficient because a substring shares its storage with the original string. The Substring
type presents the same interface as String
, so you can avoid or defer any copying of the string’s contents.
The following example creates a greeting
string, and then finds the substring of the first sentence:
You can perform many string operations on a substring. Here, we find the length of the first sentence and create an uppercase version.
Converting a Substring to a String
This example defines a raw
string with some unstructured data, and then uses the string’s prefix(while:)
method to create a substring of the numeric prefix:
When you need to store a substring or pass it to a function that requires a String
instance, you can convert it to a String
by using the String(_:)
initializer. Calling this initializer copies the contents of the substring to a new string.
Alternatively, you can convert the function that takes a String
to one that is generic over the String
protocol. The following code declares a generic version of the parse
function:
You can call this generic function with an instance of either String
or Substring
.
Important
Don’t store substrings longer than you need them to perform a specific operation. A substring holds a reference to the entire storage of the string it comes from, not just to the portion it presents, even when there is no other reference to the original string. Storing substrings may, therefore, prolong the lifetime of string data that is no longer otherwise accessible, which can appear to be memory leakage.