Swift example

How to get the length of a string in Swift

8 min read Updated Dec 2026 Runs in an isolated runtime
Quick answer

Use count: "Swift".count is 5. It counts Characters, the letters and symbols a reader sees, so "cafΓ©".count is 4 and the family emoji "πŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦".count is 1. For other lengths, ask a view: text.utf16.count is what NSString, NSRange and JavaScript count, and text.utf8.count is the size in bytes. To test for an empty string, use text.isEmpty.

Swift has no length property on String, because "length" has more than one honest answer. The family emoji is one symbol on screen, 7 Unicode scalars, 11 UTF-16 code units and 25 bytes of UTF-8, and Swift lets you ask for each of them. count gives the first, which is what a person means by "how many characters". The sections below cover count, the four lengths side by side, why emoji, flags and accents behave the way they do, the UTF-16 length that NSRange needs, byte lengths for storage limits, and what count costs, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.

1count: the number of charactersRecommended

A Swift String is a collection of Character values, and count is the number of them. A Character is an extended grapheme cluster: one user-perceived character, however many code points it takes to build it. So an accented letter, a flag or an emoji with a skin tone each count as one, which is what you want for a username limit or a "characters left" counter. count needs no import, and a Substring has it too.

count.swift
let name = "Swift"
print(name.count)

// count is in Characters: what a reader sees as one symbol
let words = ["cafΓ©", "naΓ―ve", "πŸ‡―πŸ‡΅", "πŸ‘πŸ½", "πŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦"]
for word in words {
    print(word, word.count)
}

// isEmpty is the way to test for ""
let empty = ""
print(empty.isEmpty, empty.count)

// A length rule for user input, counted in characters
let username = "zoΓ«_92"
if (3...20).contains(username.count) {
    print("\(username) has \(username.count) characters: OK")
}

// A Substring counts the same way
let greeting = "Hello, world"
print(greeting.prefix(5).count)

Output

"Swift" gives 5, cafΓ© 4 and naΓ―ve 5 count the accented letters once, and the flag, the thumbs-up with a skin tone and the family each count as 1. The empty string prints true 0. The username check accepts zoΓ«_92 with 6 characters, the number a person would count. If you need a different number, such as the length an API in another language reports, count is the wrong tool; the next sections show the others.

2The four lengths of one string

Besides its characters, a string offers three views of its contents, each a collection with its own count: unicodeScalars (Unicode code points), utf16 (16-bit code units) and utf8 (bytes). For plain ASCII text all four agree, which is why code that uses the wrong one can pass its tests and break later on a name or an emoji.

four_lengths.swift
let samples = ["Swift", "cafΓ©", "€100", "πŸ‡―πŸ‡΅", "πŸ‘πŸ½", "πŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦"]

print("text: count scalars utf16 utf8")
for text in samples {
    let counts = [
        text.count,
        text.unicodeScalars.count,
        text.utf16.count,
        text.utf8.count,
    ]
    print("\(text):", counts.map(String.init).joined(separator: " "))
}

Output

Swift: 5 5 5 5 is the case where the choice doesn't matter. cafΓ© has 4 of everything except bytes: Γ© takes 2 bytes in UTF-8, and € takes 3, so €100 is 6 bytes. Emoji live outside the 16-bit range, so each scalar takes 2 UTF-16 units and 4 bytes: the flag is 1 character, 2 scalars, 4 UTF-16 units and 8 bytes. The family ends at 1 7 11 25, the biggest spread in the list.

3Why πŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦ is one character

The family emoji is not one code point. It is four people emoji glued together with invisible ZERO WIDTH JOINER scalars, and Unicode's grapheme rules say the result is one character on screen. Swift follows those rules, so it treats the whole sequence as one Character. The same happens to a flag, which is two regional indicator letters, to an emoji followed by a skin-tone modifier, and to a letter followed by a combining accent. Comparison follows the same idea: two strings are equal when they look the same, even if the scalars differ.

grapheme_clusters.swift
let family = "πŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦"
print(family.count, family.unicodeScalars.count)
for scalar in family.unicodeScalars {
    let hex = String(scalar.value, radix: 16, uppercase: true)
    print("U+\(hex)", scalar.properties.name ?? "")
}

// Two regional indicator letters (J and P) make one flag
let flag = "\u{1F1EF}" + "\u{1F1F5}"
print(flag, flag.count)

// A skin-tone modifier joins the emoji before it
let wave = "πŸ‘‹" + "\u{1F3FD}"
print(wave, wave.count)

// The same Γ©, written as one scalar and as e + combining accent
let precomposed = "\u{E9}"
let combining = "e\u{301}"
print(precomposed == combining, precomposed.count, combining.count)
print(precomposed.unicodeScalars.count, combining.unicodeScalars.count)
print(precomposed.utf8.count, combining.utf8.count)

// Searching works on Characters too
print(family.contains("πŸ‘©"))
print(family.unicodeScalars.contains("πŸ‘©"))

Output

The family is 1 7: one character built from the scalars WOMAN, WOMAN, GIRL and BOY, with a ZERO WIDTH JOINER between each pair. The two flag letters join into πŸ‡―πŸ‡΅ 1, and the skin tone joins the wave into πŸ‘‹πŸ½ 1. The two spellings of Γ© compare equal and both count as one character (true 1 1), yet one is 1 scalar and 2 bytes and the other 2 scalars and 3 bytes. The last two lines are the part that surprises people: family.contains("πŸ‘©") is false, because no Character of the string is a lone woman, while the scalar view does contain her.

4utf16.count for NSString, NSRange and JavaScript

NSString, and with it every Foundation and UIKit API that takes an NSRange (NSRegularExpression, NSAttributedString, text field delegates), measures text in UTF-16 code units. So do JavaScript's length and Java's length(). When you compare against one of those, or build a range for one, use text.utf16.count. Better still, don't build ranges from numbers at all: NSRange(range, in: text) and Range(nsRange, in: text) convert between Swift ranges and NSRange correctly. These need import Foundation.

utf16_nsrange.swift
import Foundation

let text = "Hi πŸ‘‹πŸ½, I'm ZoΓ«"
print("count:", text.count)
print("utf16.count:", text.utf16.count)
print("NSString length:", (text as NSString).length)

// Build the NSRange from the string, not from a number
let regex = try NSRegularExpression(pattern: "Zo.")
let whole = NSRange(text.startIndex..., in: text)
print("whole range:", whole.location, whole.length)
if let match = regex.firstMatch(in: text, range: whole),
   let range = Range(match.range, in: text) {
    print("found", text[range], "at UTF-16 offset", match.range.location)
}

// A range built from count stops short of the end
let short = NSRange(location: 0, length: text.count)
let found = regex.firstMatch(in: text, range: short) != nil
print("with count as the length, found:", found)

Output

The string has 13 characters but 16 UTF-16 units, and NSString length: 16 agrees with utf16.count, not with count. The range built with NSRange(text.startIndex..., in: text) covers all 16, and the regex finds ZoΓ« at offset 13, a UTF-16 offset that is not the character position (that would be 10). The last line is the classic bug: a range of length text.count ends 3 units early, right before ZoΓ«, so the search finds nothing. On older Stack Overflow answers you will see (text as NSString).length; text.utf16.count gives the same number without the cast.

5Byte length for storage and size limits

Database columns, network payloads, push notification bodies and file formats limit size in bytes, and text goes over the wire as UTF-8. text.utf8.count is that size, with no encoding step and no import. Foundation's lengthOfBytes(using:) gives the same number for .utf8 and also handles other encodings. To fit text into a byte limit, cut on Character boundaries: chopping the UTF-8 bytes directly can split a letter or an emoji in half.

byte_length.swift
import Foundation

let bio = "CafΓ© β˜•οΈ in ZΓΌrich πŸ‡¨πŸ‡­"
print("characters:", bio.count)
print("utf8 bytes:", bio.utf8.count)
print("lengthOfBytes .utf8:", bio.lengthOfBytes(using: .utf8))
print("lengthOfBytes .utf16:", bio.lengthOfBytes(using: .utf16))

// Keep the whole characters that fit in maxBytes of UTF-8
func prefix(_ text: String, maxBytes: Int) -> Substring {
    var used = 0
    var end = text.startIndex
    for character in text {
        used += character.utf8.count
        if used > maxBytes { break }
        end = text.index(after: end)
    }
    return text[..<end]
}

for limit in [4, 5, 12, 26] {
    let cut = prefix(bio, maxBytes: limit)
    print("limit \(limit): [\(cut)] \(cut.utf8.count) bytes")
}

// Cutting the bytes directly splits the Γ©
let raw = String(decoding: bio.utf8.prefix(4), as: UTF8.self)
print("raw cut: [\(raw)] \(raw.utf8.count) bytes")

Output

18 characters take 32 bytes of UTF-8: the coffee cup alone is 6 (the cup plus an invisible variation selector) and the Swiss flag 8. lengthOfBytes(using: .utf8) agrees with utf8.count, and UTF-16 needs 44. With a limit of 4, prefix returns Caf, because Γ© doesn't fit whole; with 26 it stops before the flag at 24 bytes. The raw cut keeps the first byte of Γ©, which is not valid UTF-8 on its own, so decoding turns it into the replacement character οΏ½, and the result is now 6 bytes, larger than the limit it was cut to.

6isEmpty, and what count costs

Finding character boundaries means walking the text, so count on a String is O(n): it reads the whole string every time you call it. isEmpty only checks whether there is a first character, so it is O(1) and says what you mean; use it instead of count == 0. For a maximum length, text.dropFirst(limit).isEmpty stops after limit characters instead of counting all of them. When you need the count of a long string more than once, store it in a constant.

is_empty.swift
import Foundation

let inputs = ["", "   ", "ok", "a comment that runs past the limit"]
for input in inputs {
    let blank = input.trimmingCharacters(in: .whitespacesAndNewlines)
        .isEmpty
    // At most 10 characters, without counting them all
    let fits = input.dropFirst(10).isEmpty
    print("\"\(input)\" empty: \(input.isEmpty) blank: \(blank) fits: \(fits)")
}

// count walks the whole string: compute it once, outside loops
let page = String(repeating: "na", count: 500_000)
let length = page.count
print(length, length == page.utf8.count)

// An optional string: treat nil as empty
let nickname: String? = nil
print(nickname?.isEmpty ?? true, nickname?.count ?? 0)

Output

Only "" is empty: true; three spaces are not empty, but they are blank: true after trimmingCharacters(in:), which needs import Foundation. The long comment fails the 10-character check with fits: false. The page of a million characters prints 1000000 true: for ASCII text the character count and the byte count match. utf8.count on a native Swift string is read from its storage without a walk, which makes it a cheap first check when you only need an upper bound. A nil nickname reads as empty with a count of 0.

7Which should you use?

MethodCountsπŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦ givesBest for
text.countCharacters1What users see: limits, counters, UI
text.isEmptyNothing (O(1))falseTesting for an empty string
text.utf16.countUTF-16 code units11NSString, NSRange, JavaScript, Java
text.utf8.countBytes25Storage, network and file size limits
text.unicodeScalars.countCode points7Unicode processing, code-point limits
lengthOfBytes(using:)Bytes in an encoding25 (.utf8)Encodings other than UTF-8 (Foundation)

Frequently asked questions

Why doesn't a Swift String have a length property?

Because the length depends on what you count, so Swift makes you choose: count for characters, utf16.count, utf8.count or unicodeScalars.count for the encodings. Writing text.length fails with "value of type 'String' has no member 'length'". Old answers use countElements(text) (Swift 1) or text.characters.count (Swift 2 and 3); today characters fails with "'characters' is unavailable: Please use String directly". Use text.count.

Why are emoji like πŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦ treated strangely in Swift strings?

Because Swift counts what you see. The family emoji is 7 Unicode scalars (four people joined by zero width joiners), but on screen it is one symbol, so count is 1. A flag (two regional indicators), an emoji with a skin tone, and a letter with a combining accent each form one Character the same way. A side effect: family.contains("πŸ‘©") is false, while family.unicodeScalars.contains("πŸ‘©") is true.

Why does Swift give a different length than JavaScript or NSString?

JavaScript's length, Java's length() and NSString.length count UTF-16 code units, and every emoji takes two of them. Swift's count counts characters. For "Hi πŸ‘‹πŸ½, I'm ZoΓ«", count is 13 and utf16.count is 16, the number those APIs report. Use text.utf16.count when you need to match them, and NSRange(range, in: text) to build an NSRange.

Is String.count O(1) in Swift?

No. A String is not random access: finding character boundaries means reading the text, so count is O(n) and runs again on every call. isEmpty is O(1). Store the count in a constant when you need it more than once, and check a maximum with text.dropFirst(limit).isEmpty, which stops after limit characters.

How do I get the size of a string in bytes?

Use text.utf8.count for UTF-8, which is what files, JSON and most network APIs use. text.lengthOfBytes(using: .utf8) from Foundation gives the same number and accepts other encodings, such as .utf16. To cut text to a byte limit, add whole characters until the next one would not fit, so you never split a letter or emoji.

How do I count how many times a character appears in a string?

Filter and count: "hello".filter { $0 == "l" }.count is 2. Since Swift 6.0 you can write "hello".count(where: { $0 == "l" }), which gives the same 2 without building a new string.

How do I get the length of an optional String?

Use optional chaining with a default: name?.count ?? 0. To test for "nil or empty" in one go, write name?.isEmpty ?? true.

Run it yourself

Open any of these in the full Swift editor to tweak, run and share.

Swift playground