Swift
Substring
String Manipulation
Programming
Coding

Index of a substring in a string with Swift

Interview Questions practice on Codemia

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

Browse interview questions

Introduction

Finding a substring index in Swift requires understanding String.Index instead of integer offsets. Swift strings are Unicode-correct, so direct integer indexing is intentionally unsupported to avoid invalid grapheme slicing.

Short troubleshooting answers often solve the immediate error but miss maintainability concerns such as reproducibility, observability, and rollback safety. A complete implementation should make assumptions explicit, validate edge cases, and produce diagnostics that are useful during incidents.

When adapting snippets, verify version compatibility, runtime environment, and operational limits before rollout. Small contextual differences, such as framework version, deployment topology, or data shape, can change behavior significantly.

Core Sections

1. Establish a minimal correct solution

Use range(of:) to find a substring and then convert to an integer offset only when needed for interoperating with external APIs.

swift
1let text = "hello swift world"
2if let r = text.range(of: "swift") {
3    let offset = text.distance(from: text.startIndex, to: r.lowerBound)
4    print("index:", offset)
5} else {
6    print("not found")
7}

This baseline should stay intentionally simple so correctness is easy to verify. Once the minimal behavior is confirmed, extend it with error handling and performance considerations rather than starting with complex abstractions.

2. Harden for production requirements

For repeated search or case-insensitive matching, use options and avoid manual loops unless you need custom tokenization behavior.

swift
1let source = "Alpha beta GAMMA"
2if let r = source.range(of: "gamma", options: [.caseInsensitive]) {
3    let matched = source[r]
4    print(matched)
5}
6
7let hasBeta = source.localizedCaseInsensitiveContains("beta")
8print(hasBeta)

Production hardening usually includes explicit validation, clear failure semantics, and safe resource lifecycle management. It also helps to centralize configuration and shared logic so behavior remains consistent across environments and teams.

3. Validate and operate with confidence

When bridging to NSString, document encoding assumptions and index conversions carefully. Bugs often appear when integer offsets computed from Unicode scalars are applied to user-perceived characters.

Add a practical verification loop with one happy-path test, one edge-case test, and one failure-path test. Pair tests with lightweight runtime signals such as error rates, latency percentiles, or startup checks so regressions are detected early.

Operational readiness includes rollback planning. Even correct code may fail under unexpected dependencies or data. Documenting rollback steps and fallback behavior reduces recovery time and deployment risk.

Implementation depth also includes long-term operability. Define clear ownership of configuration, data contracts, and failure handling so support engineers can diagnose issues without reverse engineering intent from old commits. Where possible, capture representative input and output examples in tests, because executable examples age better than prose-only documentation.

For production systems, add lightweight observability close to the critical path: structured logs for key decisions, counters for failure categories, and latency metrics around expensive operations. These signals should map to user impact directly so on-call responders can prioritize correctly under pressure. Strong observability turns debugging from guesswork into a bounded investigation.

Finally, prepare rollback and fallback behavior before deploying significant changes. Even technically correct updates can fail due to environment differences, data anomalies, or dependency upgrades. A preplanned rollback path, feature flag, or degraded-mode strategy reduces mean time to recovery and allows teams to iterate quickly without risking prolonged outages.

For teams working with user-generated text, include tests covering emoji, accented characters, and multi-script content. These cases validate that index calculations remain correct under real Unicode inputs and prevent subtle production bugs in search, highlighting, or substring extraction features.

Common Pitfalls

  • Trying to subscript Swift strings with integer indices directly.
  • Assuming ASCII-only behavior in multilingual text.
  • Using utf16 offsets without clear conversion boundaries.
  • Ignoring optional results from range(of:) and force-unwrapping.
  • Mixing NSString and Swift index semantics without tests.

Summary

Use range(of:) and Swift-native string indices for safe substring lookup. Convert to integer offsets only when required and with clear Unicode-aware boundaries. Pair implementation detail with testing and operational safeguards so the solution remains reliable as code, dependencies, and infrastructure evolve.


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

All Rights Reserved.