Sling Academy
Home/Swift/Swift: 4 Ways to Find the Length of a String

Swift: 4 Ways to Find the Length of a String

Last updated: February 23, 2023

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

Next Article: 2 Ways to Reverse a String in Swift

Series: Working with Strings in Swift

Swift

You May Also Like

  • How to Find the Union of 2 Sets in Swift
  • How to Find the Intersection of 2 Sets in Swift
  • Subtracting 2 Sets in Swift (with Examples)
  • Swift: Removing Elements from a Set (4 Examples)
  • Swift: Checking if a Set Contains a Specific Element
  • Swift: Counting the Number of Elements in a Set
  • Adding new Elements to a Set in Swift
  • How to Create a Set in Swift
  • Swift: Converting a Dictionary into an Array
  • Merging 2 Dictionaries in Swift
  • Swift: Check if a key exists in a dictionary
  • Swift: Removing a key-value pair from a dictionary
  • Swift: Adding new key-value pairs to a dictionary
  • Swift: Counting Elements in a Dictionary
  • Swift: Ways to Calculate the Product of an Array
  • Swift: How to Convert an Array to JSON
  • Swift: Different ways to find the Min/Max of an array
  • Swift: 4 Ways to Count the Frequency of Array Elements
  • How to Compare 2 Arrays in Swift (Basic & Advanced)