How to find the length of a string in Swift

Overview

The number of characters that make up a string is the length of that string. We can find this in Swift through the count property. It returns this number.

Syntax

string.count

Return value

The value returned is an integer. It is the number of characters a string has.

Code example

// create strings
let str1 = "Edpresso"
let str2 = "is"
let str3 = "awesome!"
let str4 = ""
// check length of strings
// and print result
print(str1.count) // 8
print(str2.count) // 2
print(str3.count) // 8
print(str4.count) // 0

Explanation

  • Lines 2-5: We create some strings.
  • Lines 9-12: We check the length of the strings using the count property and print the results.
New on Educative
Learn any Language for FREE all September 🎉
For the entire month of September, get unlimited access to our entire catalog of beginner coding resources.
🎁 G i v e a w a y
30 Days of Code
Complete Educative’s daily coding challenge every day in September, and win exciting Prizes.

Free Resources