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:

The implementation is quite simple:

Swift 4

It’s just:

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:

Swift 1

Use the count characters method:

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:

Or you can use:

Sumary

Swift 1.1

Swift 1.2

Swift 2.0

Swift 4.2