Why this happens
Older Swift code used methods such as substring(to:), substring(from:), and substring(with:) to extract part of a string. Swift 4 deprecated these methods in favor of string subscripts that accept ranges. The range-based syntax remains the appropriate replacement in modern Swift.
When migrating older code, you may encounter the diagnostic 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator. Despite that wording, preserving the behavior of substring(to:) requires ..<index, not index...: the former selects everything before the index, while the latter selects everything starting at it.
There is also a return-type change to account for. A slice of a String is a Substring, not another String. Both support string operations, but a function or property explicitly requiring String needs a conversion.
How to fix it
1. Replace substring(to:) with a partial range up to the index
For the original example, find the comma and use it as the exclusive upper bound of the slice:
let text = "Hello, playground"
if let commaIndex = text.firstIndex(of: ",") {
let result = text[..<commaIndex]
print(result) // Hello
}
The expression ..<commaIndex is a one-sided, or partial, range. Its lower bound is omitted, so the string subscript starts at text.startIndex. The < means the character at commaIndex is excluded.
The direct replacement is:
// Deprecated:
// text.substring(to: commaIndex)
// Replacement, when commaIndex is a valid index into text:
// text[..<commaIndex]
Use firstIndex(of:) when updating the older index(of:) lookup shown in legacy examples. Optional binding also avoids a crash if the input does not contain a comma.
If you want to keep the entire input when no comma exists, make that fallback explicit:
let text = "Hello, playground"
let boundary = text.firstIndex(of: ",") ?? text.endIndex
let result = text[..<boundary]
print(result) // Hello
Using endIndex as an exclusive upper bound is valid. If there is no comma, this slice covers the whole string.
2. Convert the slice to String when required
The accepted replacement returns a Substring. Wrap it in String(...) when assigning it to a String property, passing it to an API that requires String, or storing the extracted text independently:
let text = "Hello, playground"
let boundary = text.firstIndex(of: ",") ?? text.endIndex
let greeting: String = String(text[..<boundary])
print(greeting) // Hello
A helper can keep both the conversion and missing-delimiter behavior in one place:
func textBeforeComma(in text: String) -> String {
let boundary = text.firstIndex(of: ",") ?? text.endIndex
return String(text[..<boundary])
}
print(textBeforeComma(in: "Hello, playground")) // Hello
print(textBeforeComma(in: "Hello")) // Hello
A Substring can share storage with its source string. That makes it useful for temporary parsing, but retaining a small substring can also keep the original string’s storage alive. Converting a result you plan to keep into a String avoids retaining the source buffer through that substring.
You do not need to convert every slice immediately. For a local comparison, inspection, or printing operation, keeping the Substring is often sufficient.
3. Match the range direction to the old method
The other deprecated substring methods follow the same pattern, but their bounds differ:
| Old method | Range-based replacement | Behavior |
|---|---|---|
text.substring(to: index) |
text[..<index] |
Everything before the index |
text.substring(from: index) |
text[index...] |
Everything from the index onward |
text.substring(with: range) |
text[range] |
Characters inside the supplied range |
For a slice starting at the comma, use a partial range from the index:
let text = "Hello, playground"
if let commaIndex = text.firstIndex(of: ",") {
let suffix = String(text[commaIndex...])
print(suffix) // , playground
}
Notice that the comma remains in the result. index... includes the character at its lower bound.
To exclude the delimiter, advance by one character before slicing:
let text = "Hello, playground"
if let commaIndex = text.firstIndex(of: ",") {
let afterComma = text.index(after: commaIndex)
let suffix = String(text[afterComma...])
print(suffix) // playground
}
The leading space remains because it belongs to the original text. Slicing selects a range; it does not trim whitespace.
For a bounded range, supply both indices:
let text = "Hello, playground"
if let spaceIndex = text.firstIndex(of: " ") {
let start = text.index(after: spaceIndex)
let range = start..<text.endIndex
let word = String(text[range])
print(word) // playground
}
4. Use character-based operations for fixed-length prefixes
Swift strings do not support integer character subscripts such as text[0..<5]. String positions use String.Index because a visible character can contain multiple Unicode scalars and occupy a variable amount of encoded storage.
If your actual task is “take the first five characters,” prefix(_:) is clearer than manually calculating an index:
let text = "Hello, playground"
let prefix = String(text.prefix(5))
print(prefix) // Hello
prefix(_:) also handles an input shorter than the requested count by returning the available characters. Use range subscripts when you already have meaningful boundaries, such as the position of a comma. Use prefix(_:) when the requirement is a character count.
How to prevent it
- Replace deprecated substring calls according to their direction;
to:andfrom:are not interchangeable. - Use indices obtained from the string you are slicing, and do not assume saved indices remain valid after mutation.
- Handle a missing delimiter with optional binding or an explicit fallback instead of
!. - Convert temporary slices to
Stringwhen your API contract or longer-lived storage requires it. - Test empty input, missing delimiters, delimiters at either end, and text containing emoji or combining marks.
FAQ
Does substring(to:) include the character at the index?
No. Its equivalent is text[..<index], which excludes the upper-bound character. To include a character at a known valid character index, use text[...index]; do not use endIndex as an inclusive character position.
Why does the replacement produce Substring instead of String?
String slicing returns Substring so a slice can share storage with its source rather than immediately creating independent string storage. Use String(slice) when you need a String, especially for an explicitly typed property or a result you intend to retain.
What happens if the delimiter is the first or last character?
If the delimiter is first, text[..<delimiterIndex] produces an empty substring. If it is last, advancing once with index(after:) reaches endIndex, and slicing text[endIndex...] also produces an empty substring; neither case needs a force unwrap or special nonempty-string assumption.
Parts of this guide are adapted from content licensed under CC BY-SA 4.0; this article is shared under the same license.