Swift
String Manipulation
Substring
Swift 4
String Slicing

How can I use String substring in Swift 4? 'substringto' is deprecated Please use String slicing subscript with a 'partial range from' operator

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Swift is a powerful and intuitive programming language for iOS, macOS, watchOS, and tvOS app development, and it offers many features to make your code concise and expressive. String manipulation is a fundamental part of programming, and with Swift 4, Apple introduced a new way to handle substrings. This was a significant change from earlier versions which used methods like substring(to:), which have since been deprecated. Let's explore how to work with substrings in Swift 4 using string slicing and range operators.

Understanding String Slicing

In Swift 4, the process of obtaining substrings shifted towards using slicing with indices and range operators. Strings in Swift are not indexed by integers but by a special type called String.Index. This design decision allows indexing to work accurately with mixed-character-length strings like those including emojis or different script languages.

Obtaining a Substring

Instead of using deprecated methods, we now slice strings using the appropriate String.Index. Here’s how you can obtain a substring with slicing:

swift
1let fullString = "Hello, Swift World!"
2let endIndex = fullString.index(fullString.startIndex, offsetBy: 5)
3let substring = fullString[..<endIndex]
4print(substring)  // Output: "Hello"

Explanation

  • Indexing: We use String.index(_:offsetBy:) to find the desired String.Index.
  • Range Operator: The range operator ..< is used to create a range up to, but not including, the specified index.
  • Substring Type: The result is of type Substring, which shares the storage of the original string. This makes operations more efficient until you convert it to String if needed.

Converting Substring to String

For certain operations, you might need a String type instead of Substring. Conversion is straightforward:

swift
let stringPortion = String(substring)

Using Partial Range Up To Operator

Alternatively, you can utilize the partial range from operator with slices:

swift
let partialSubstring = fullString.prefix(5)
print(partialSubstring)  // Output: "Hello"

Why Substring(to:) is Deprecated

The method substring(to:) was part of the earlier string API, which was less safe and less efficient. Swift 4 advocates for using String.Index and range subscripts, providing more control over performance and memory.

Table: Key Operators and Methods

Operator/MethodDescriptionExample Usage
..<Half-open range up to a given indexstring[..<index]
...Closed range including the last indexstring[start...end]
prefix(_:)Returns a substring from the startstring.prefix(3)
suffix(_:)Returns a substring from the endstring.suffix(3)
String.index(_:offsetBy:)Computes index from another with offsetstring.index(start, offsetBy:5)

Additional Considerations

Performance

When slicing strings, Swift uses Substring, which shares the original string's storage. This shared storage means that the original string cannot be deallocated as long as there's a substring referencing it. Keep this in mind when dealing with large strings or memory-sensitive operations, and convert Substring to a String where necessary.

Unicode Compliance

Swift handles character encoding using UTF-8, ensuring that string operations respect multibyte character boundaries. When working with strings involving such characters, Swift’s approach ensures you don't inadvertently split characters.

String Interpolation

String slicing can be combined with string interpolation for dynamic content:

swift
let name = "World"
let greeting = "Hello, \(name.prefix(3))!"
print(greeting) // Output: "Hello, Wor!"

By understanding and leveraging Swift's slicing capabilities, you can take full advantage of its robust and modern string handling mechanisms. This change aligns with Swift’s goals of safety, performance, and clarity, and gives you powerful tools for effective string manipulation.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions