To get the length of a given string in Swift, you can use the count
property of the String class.
In this example,
str1
with a string value of "Hello World"
.count
property of the string object str1
to get the length of the string and store the returned value in the variable length1
.count
property returns the length of this string.length1
to the console using print()
.// Length of "Hello World" String
let str1 = "Hello World"
let length1 = str1.count
print("Length of given string is: \(length1)")
Length of given string is: 11
In this example,
str2
with a string value of "apple"
.count
property of the string object str2
to get the length of the string and store the returned value in the variable length2
.count
property returns the length of this string.length2
to the console using print()
.// Length of "apple" String
let str2 = "apple"
let length2 = str2.count
print("Length of given string is: \(length2)")
Length of given string is: 5
In this tutorial, we learned How to get Length of String in Swift language with well detailed examples.