Swift: 4 Ways to Find the Length of a String

Updated: February 23, 2023 By: Khue Post a comment

This concise, example-focused article walks you through 4 different approaches to getting the length of a given string in Swift. Without any further ado, let’s get our hands dirty with code.

Using the “count” property

The simplest way to find the length of a string in Swift is to use the count property, which returns the number of characters in the string.

Example:

let str = "Sling Academy is where you can learn magic and become a wizard."
let length = str.count
print(length)

Output:

63

Using a “for” loop

Using a for loop to determine the length of a string may seem more cumbersome than necessary, but it’s also helpful to know another way to solve a problem.

Example:

let str = "One locked room, one loaded gun, one bullet, one chance to escape."
var length = 0

for _ in str {
    length += 1
}

print(length) 

Output:

66

Using the unicodeScalars property

In case you want to find the length of a string based on the number of Unicode scalar values it contains, you can use the unicodeScalars property, which returns a collection of Unicode scalar values that make up the string. You can then count the number of elements in this collection to find the length of the string.

Example:

let str = "Behold the turtle. He makes progress only when he sticks his neck out."
let length = str.unicodeScalars.count
print(length)

Output:

70

Using the utf16 property

In scenarios where you need to find the length of a string based on the number of UTF-16 code units it contains, you can use the utf16 property, which returns a collection of UTF-16 code units that make up the string. To get the length of the string, just count the number of elements in this collection.

Example:

let str = "ajf ljdjl jd fdjf jldl"
let length = str.utf16.count
print(length) 

Output:

22