How to Find String Length in Swift
To find the length of a string in Swift, use the string’s count property. It returns the number of Swift Character values in the string.
string.count
The result is an Int. Spaces, punctuation marks, line breaks, letters, and user-perceived characters such as many emoji are included in the count.
Swift String count syntax and return value
Read the count property from any String value:
let length: Int = text.count
No parentheses are required because count is a property, not a method. Therefore, write text.count, not text.length() or text.count().
Example 1 – String length
In the following example, we take a string in variable str and find its length using count property.
main.swift
var str = "Hello World"
var len = str.count
print( "Length of str is \(len)" )
Output
Length of str is 11
The result is 11 because the space between Hello and World is also a character.
Count characters in a Swift string containing emoji
Swift strings are Unicode-correct. The count property measures Character values rather than the number of bytes used to store the text.
let text = "Swift 🚀"
print(text.count)
print(text.utf8.count)
print(text.utf16.count)
Output
7
10
8
Here, text.count returns 7: five letters, one space, and one rocket emoji. The UTF-8 and UTF-16 views return different values because they count code units in those encodings.
Swift String count with extended grapheme clusters
A single visible character can be formed from multiple Unicode scalars. Swift groups those scalars into an extended grapheme cluster and usually treats the complete cluster as one Character.
let family = "👨👩👧👦"
let accentedLetter = "e\u{301}"
print(family.count)
print(accentedLetter.count)
Output
1
1
The family emoji contains several Unicode scalars joined into one displayed character. The accented letter is composed from e and a combining accent, but Swift also counts it as one Character.
Check whether a Swift string is empty
You can test whether count equals zero, but Swift provides the clearer isEmpty property for this specific check.
let username = ""
if username.isEmpty {
print("Username is empty")
}
Output
Username is empty
Use isEmpty when you only need a Boolean answer. Use count when you need the actual number of characters.
Validate minimum and maximum Swift string length
The count property can be used to validate input such as usernames, labels, and short messages.
let username = "swift_user"
let minimumLength = 4
let maximumLength = 15
if username.count < minimumLength {
print("Username is too short")
} else if username.count > maximumLength {
print("Username is too long")
} else {
print("Username length is valid")
}
Output
Username length is valid
This validates the number of Swift characters. A server or external protocol may instead define limits in UTF-8 bytes or another encoding, so use the corresponding string view when that distinction matters.
Find the length of a Swift substring
Operations such as prefix, suffix, and slicing often produce a Substring. A substring also has a count property.
let language = "Swift Programming"
let firstWord = language.prefix(5)
print(firstWord)
print(firstWord.count)
Output
Swift
5
Swift String count versus UTF-8, UTF-16, and Unicode scalar counts
| Expression | What it counts | Typical use |
|---|---|---|
text.count | Swift Character values | User-visible character limits and normal string processing |
text.unicodeScalars.count | Unicode scalar values | Unicode-level inspection |
text.utf8.count | UTF-8 code units, equivalent to bytes | UTF-8 storage or protocol byte limits |
text.utf16.count | UTF-16 code units | Interoperation with UTF-16-based APIs |
These counts can be equal for simple ASCII text and different for accented characters, non-Latin scripts, and emoji. Choose the view that matches the requirement you are implementing.
Performance considerations for Swift String count
Do not assume that obtaining a Swift string’s character count is always a constant-time operation. Unicode characters have variable-width representations, and Swift may need to examine the string to determine its character boundaries.
If the same large string is checked repeatedly inside performance-sensitive code, calculate the count once and store the result. For a simple empty-string check, prefer isEmpty.
let message = "A long string used several times"
let characterCount = message.count
if characterCount > 10 {
print("The message has \(characterCount) characters")
}
Common mistakes when checking Swift string length
- Calling
length(): Swift uses thecountproperty for strings. - Writing
count():countis accessed without parentheses. - Assuming count means bytes:
String.countreturns characters, whileutf8.countreturns UTF-8 bytes. - Ignoring spaces and punctuation: They are included in the character count.
- Using integer indexes with String: Swift string indexes are not plain integer offsets because characters can have variable-width representations.
Swift string length frequently asked questions
How do I check the length of a string in Swift?
Use string.count. It returns an Int containing the number of Swift Character values in the string.
Does Swift String count include spaces?
Yes. Spaces, tabs, line breaks, and punctuation are characters and are included when present in the string.
Does Swift String count return the number of bytes?
No. It returns the number of Character values. Use string.utf8.count when you specifically need the number of UTF-8 bytes.
Why can one emoji have a Swift string count of one?
Swift models a displayed character as an extended grapheme cluster. An emoji made from multiple Unicode scalars can therefore be represented as one Character.
Should I use count == 0 or isEmpty in Swift?
Use isEmpty when checking only whether a string has no characters. It states the intent directly. Use count when the numeric length is required.
Swift string length editorial QA checklist
- Verify that every example uses
String.countwithout parentheses. - Confirm that examples distinguish character count from UTF-8 and UTF-16 code-unit counts.
- Test emoji and combining-character examples with a current Swift compiler.
- Check that output values include spaces and punctuation where applicable.
- Use
isEmptyinstead of calculating a count when an example only tests for an empty string.
Using String count correctly in Swift
Use string.count for the number of Swift characters in a string. Use isEmpty for an empty-string test, and use the utf8, utf16, or unicodeScalars view when a requirement is defined in encoding units rather than characters. In this Swift Tutorial, we have learned to get the length of a String using count property with the help of Swift example programs.
TutorialKart.com