Swift
String manipulation
Array splitting
Subarray
Swift programming

Swift what is the right way to split up a String resulting in a String with a given subarray size?

Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms

Introduction

Chunking a Swift string into fixed-size pieces looks simple until you account for Unicode. Swift strings are collections of extended grapheme clusters rather than plain byte arrays, so the correct solution walks through String.Index values instead of trying to slice by raw integer offsets.

Why Integer Slicing Is Not the Right Model

A visible character in Swift may use multiple Unicode scalars and multiple bytes. That means the "third character" is not safely equivalent to the third byte in memory.

swift
1import Foundation
2
3let text = "Café🙂Swift"
4print(text.count)
5print(text.utf8.count)

These counts can differ. count measures user-visible characters, while utf8.count measures bytes. That is why Swift does not let you subscript a String with plain integers.

Build Chunks with String.Index

A safe chunking function should:

  • reject non-positive chunk sizes
  • preserve character boundaries
  • keep the trailing partial chunk if one remains
swift
1import Foundation
2
3extension String {
4    func chunked(by size: Int) -> [String] {
5        guard size > 0 else { return [] }
6
7        var result: [String] = []
8        var start = startIndex
9
10        while start < endIndex {
11            let end = index(start, offsetBy: size, limitedBy: endIndex) ?? endIndex
12            result.append(String(self[start..<end]))
13            start = end
14        }
15
16        return result
17    }
18}
19
20print("abcdefghij".chunked(by: 3))
21print("🙂🙂🙂🙂🙂".chunked(by: 2))

This works because it moves across valid Swift string indexes instead of pretending the string is an array of bytes.

Understand What the Output Means

For a plain ASCII example, the result is straightforward.

  • '"abcdefghij" becomes [ "abc", "def", "ghi", "j" ]'

For emoji or accented text, the function still behaves correctly because each chunk boundary is based on character-aware indexing rather than raw storage layout.

That is the main reason this approach is the right one for user-visible text.

Do Not Confuse String Chunking with Token Grouping

Sometimes the real problem is not chunking one continuous string. It is splitting by a delimiter and then grouping the resulting tokens. That is a different task.

swift
1import Foundation
2
3extension Array {
4    func chunked(by size: Int) -> [[Element]] {
5        guard size > 0 else { return [] }
6
7        var result: [[Element]] = []
8        var i = 0
9
10        while i < count {
11            let end = Swift.min(i + size, count)
12            result.append(Array(self[i..<end]))
13            i = end
14        }
15
16        return result
17    }
18}
19
20let csv = "alpha,beta,gamma,delta,epsilon"
21let tokens = csv.split(separator: ",").map(String.init)
22print(tokens.chunked(by: 2))

Here the chunking happens on an array of tokens, not on the original raw string. That distinction matters because the indexing rules are different.

Choose the Right Abstraction

If your actual requirement is byte-oriented, such as network framing or binary file parsing, String is the wrong abstraction. In those cases, use Data and chunk bytes directly.

String chunking is appropriate when the unit of interest is text characters that should remain readable and valid.

Keep the Helper Reusable

Unicode-safe index math is not code you want repeated throughout the project. A small String extension keeps the logic centralized and easy to test.

That also reduces the chance that someone later reintroduces unsafe byte-based slicing in one specific call site.

Common Pitfalls

A common mistake is trying to subscript a Swift string with integer indexes as if it were an array. Swift disallows that because it would make Unicode handling unreliable.

Another is confusing character chunking with delimiter-based splitting. Those are different operations and should usually be handled by different helpers.

It is also easy to forget to reject size 0. If the chunk size is not positive, a loop based on advancing indexes can become invalid or non-terminating.

Summary

  • Swift strings must be sliced with String.Index, not integer offsets.
  • A correct chunking helper should advance indexes with offsetBy and limitedBy.
  • Use string chunking for user-visible text, not for byte-oriented protocols.
  • Group already-split tokens separately if the real problem is array chunking.
  • Reject zero or negative chunk sizes.

Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms