Difficulty: Beginner | Easy | Normal | Advanced
A Substring is a portion of a String, and Swift Substring provides a convenient way to manipulate and extract these smaller segments. Within this article, we will explore Substrings and how to convert Substrings to Strings.
Related topics in series:
- Turn Swift String to Data
- Swift String to Int
- Swift String to Array
- Swift String concatenation
- Swift String Interpolation
What is a Substring in Swift?
Swift has its own dedicated type, that holds a smaller portions of strings. For instance, imagine you had the String “Apple”, and you just wanted a part of it e.g. “App”. The smaller portion “App” is a Substring. In Swift, a substring is like a smaller piece of a bigger word or sentence that you can work with.
Why use Substrings
Substrings are handy because they let you work with just a part of a word or sentence without making a whole new copy of it.
How Substrings work
Swift Strings are value types, meaning that if you use one String to make a new one, then it is copied over. Whereas, a Substring, on the other hand, is a reference back to the original String from which it came.
A substring can reuse part of the memory that’s used to store the original string, or part of the memory that’s used to store another substring…. substrings aren’t suitable for long-term storage — because they reuse the storage of the original string, the entire original string must be kept in memory as long as any of its substrings are being used.
Creating a Substring
In the example belo, you can utilise the prefix method to return a subsequence from the start of a collection to the specified position:
Converting a Substring to a String
Converting a Swift Substring to a String is extremely straight forward, you can use the String initialiser.
Summary
Substrings in Swift are smaller pieces of a larger text. They are value types, which means they are independent of the original text and can be used for efficient manipulation without altering the original string.