Get the length of a String in Swift

i0S Swift Issue

How to get the length of characters of a string is a common question for Swift beginners.

For example, you declare a string type variable as follows:

var Text01: String = "izziswift"

The implementation is quite simple:

Swift 4

It’s just:

Text01.count

Swift 2

With Swift 2, Apple has changed global functions to protocol extensions, extensions that match any type conforming to a protocol. Thus the new syntax is:

Text01.characters.count

Swift 1

Use the count characters method:

let Text01 = "Koala 🐨, Snail 🐌, Penguin 🐧, Dromedary 🐪"
println("Text01 has \(count(Text01)) characters")
// prints "Text01 has 40 characters"

right from the Apple Swift Guide (note, for versions of Swift earlier than 1.2, this would be countElements(Text01)instead) for your variable, it would be:

length = count(Text01) // was countElements in earlier versions of Swift

Or you can use:

 test1.utf16.count

Sumary

Swift 1.1

extension String {var length: Int { return countElements(self) }}

Swift 1.2

extension String {var length: Int { return count(self) } }

Swift 2.0

extension String {var length: Int { return characters.count } }

Swift 4.2

extension String {var length: Int { return self.count } }
let str = "Hello"
let count = str.length
// returns 5 (Int)