838

How do you get the length of a String? For example, I have a variable defined like:

var test1: String = "Scott"

However, I can't seem to find a length method on the string.

Naresh
  • 16,698
  • 6
  • 112
  • 113
Scott Walter
  • 9,426
  • 4
  • 18
  • 23
  • possible duplicate of [String length in Swift 1.2 and Swift 2.0](http://stackoverflow.com/questions/29575140/string-length-in-swift-1-2-and-swift-2-0) – King-Wizard Sep 19 '15 at 10:31
  • I had to migrate a lot of code manually because of Swift 3. So I decided to create extensions. So now, if have to upgrade to a new major release, I need to migrate only the extension. Here you can find some Swift 3 extensions I've created. https://github.com/tukur187/Swift3 – Shkelzen Dec 05 '16 at 12:51
  • Whatever solution you go for, you can [cross check the results](https://magic-tools-531.web.app/#!/tools/character-count) with an online tool – WJA Jan 02 '22 at 21:24

41 Answers41

1368

As of Swift 4+

It's just:

test1.count

for reasons.

(Thanks to Martin R)

As of 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:

test1.characters.count

(Thanks to JohnDifool for the heads up)

As of Swift 1

Use the count characters method:

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

right from the Apple Swift Guide

(note, for versions of Swift earlier than 1.2, this would be countElements(unusualMenagerie) instead)

for your variable, it would be

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

Or you can use test1.utf16count

Josh Correia
  • 3,807
  • 3
  • 33
  • 50
mginn
  • 16,036
  • 4
  • 26
  • 54
  • 11
    Interesting that countElements is a global function. Is there a list of global functions? – Scott Walter Jun 04 '14 at 13:03
  • 5
    @ScottWalter: cmd-click on a Swift symbol (ex: String) and you'll get to them. Near the top of the resulting file. – Jean Le Moignan Jun 18 '14 at 20:15
  • 301
    It was just too hard to add a str.length method. (raises his fist in anger) – botbot Dec 13 '14 at 08:57
  • @botbot: You can easily add one by extending the class. :) – Sasha Chedygov Jan 02 '15 at 18:29
  • The weird part is that Apple's document does have a length property in Swift:The number of Unicode characters in the receiver. (read-only) Declaration SWIFT var length: Int { get } – CodeBrew Jan 15 '15 at 04:17
  • @ScottWalter Dash.app, a document browser app, maintains a current list of global functions for the swift documentation set. Knowing which of those to use or what to look for isn't always obvious though. – Bjorn Jan 22 '15 at 19:03
  • 4
    countElements has been replaced by count in swift 1.2 (beta 1) There‘s no longer a separate countElements call for counting the size of collections vs count for ranges – it’s now just count for both. – Ali Abbas Feb 16 '15 at 14:02
  • `countElements` has been renamed to just `count` in Swift 1.2. – Evgenii Feb 16 '15 at 23:12
  • 5
    It's ridiculous that a "length" method wasn't added. This language is barely beta-quality, let alone release-quality. – Womble May 12 '15 at 06:11
  • 13
    With Swift 2, I can only get this to work: let len = test1.characters.count – John Difool Jun 09 '15 at 18:39
  • Yes Apple has changed global functions to protocol extensions – mginn Jun 09 '15 at 18:40
  • 3
    @milesper Note that this is an O(n) operation and *not* the same as (str as NSString).length, which is equivalent to str.utf16.count and is O(1) – Patrick Pijnappel Dec 04 '15 at 23:37
  • 3
    So Apple has changed this simple function three times in one year?! Am I the only feeling shaky ground under my feet? – Cosmin Jun 04 '16 at 14:32
  • 8
    Note that with Swift 4, it will be `string.count`. – Martin R May 19 '17 at 12:49
  • 2
    a language being made up on the fly - add some comment about swifts flying – pm100 Aug 23 '17 at 22:07
  • 3
    It's a trap! They want you to focus on constantly changing your code for new language constructs instead of focusing on productivity. And then they deprecate older constructs so that you constantly need to keep on dancing. :/ – Fredrik Johansson Nov 22 '17 at 11:21
  • test.text.count for swift 4 – Puji Wahono Jan 10 '19 at 11:10
346

TLDR:

For Swift 2.0 and 3.0, use test1.characters.count. But, there are a few things you should know. So, read on.

Counting characters in Swift

Before Swift 2.0, count was a global function. As of Swift 2.0, it can be called as a member function.

test1.characters.count

It will return the actual number of Unicode characters in a String, so it's the most correct alternative in the sense that, if you'd print the string and count characters by hand, you'd get the same result.

However, because of the way Strings are implemented in Swift, characters don't always take up the same amount of memory, so be aware that this behaves quite differently than the usual character count methods in other languages.

For example, you can also use test1.utf16.count

But, as noted below, the returned value is not guaranteed to be the same as that of calling count on characters.

From the language reference:

Extended grapheme clusters can be composed of one or more Unicode scalars. This means that different characters—and different representations of the same character—can require different amounts of memory to store. Because of this, characters in Swift do not each take up the same amount of memory within a string’s representation. As a result, the number of characters in a string cannot be calculated without iterating through the string to determine its extended grapheme cluster boundaries. If you are working with particularly long string values, be aware that the characters property must iterate over the Unicode scalars in the entire string in order to determine the characters for that string.

The count of the characters returned by the characters property is not always the same as the length property of an NSString that contains the same characters. The length of an NSString is based on the number of 16-bit code units within the string’s UTF-16 representation and not the number of Unicode extended grapheme clusters within the string.

An example that perfectly illustrates the situation described above is that of checking the length of a string containing a single emoji character, as pointed out by n00neimp0rtant in the comments.

var emoji = ""
emoji.characters.count             //returns 1
emoji.utf16.count                  //returns 2
Skeleton Bow
  • 479
  • 1
  • 9
  • 22
Cezar
  • 55,636
  • 19
  • 86
  • 87
  • 26
    I appreciate your detailed and cautionary answer, but I have to admit it's left me uneasy. You gave me 3 ways to get the length of a string, all with the disclaimer that the answers they give might not be what you expect. Is there truly no reliable way built into Swift to get an accurate, reliable length value of a string? – n00neimp0rtant Jun 06 '14 at 13:29
  • 6
    @n00neimp0rtant. Sorry if I did not make it clear. The first solution (`countElements()`)gets the exact number of characters in the String. It might be different from what you'd get from calling `[str length]` in Objective-C, because the `length` method assumes all characters in the string are composed of 16-bit code units, while `countElements()` gets the actual number of Unicode characters. However, most of the time all of the above alternatives will return the same results, specially if you're are working with English language common characters. – Cezar Jun 06 '14 at 13:32
  • 2
    @n00neimp0rtant I tweaked my answer a little bit to try and make it more clear. – Cezar Jun 06 '14 at 13:37
  • 2
    I see what you mean now. I just tried getting the length of a string containing a single Emoji character; Objective-C gave me a value of 4, and Swift gave me a value of 1. So it actually seems more accurate (and therefore, ironically "not what I'd expect" =P). Thanks for the clarification! – n00neimp0rtant Jun 06 '14 at 13:45
  • 1
    @n00neimp0rtant Exactly! That's a perfect example. I'll even add it to the answer – Cezar Jun 06 '14 at 13:52
  • I guess in the special case in which you want to determine if the string is empty or not, it doesn't really matter which method you use (i.e., the empty string has length 0 in every representation). – Nicolas Miari Jul 22 '15 at 03:12
  • 1
    ...forget about that; it turns out there is an `isEmpty` property! (just found out) – Nicolas Miari Jul 22 '15 at 03:20
  • For Swift 2.0, the "length" of a String can be returned using test1.characters.count (not test1.count). – powertoold Sep 07 '15 at 19:40
  • **'String' has no member 'bridgeToObjectiveC' ** (swift 2.2, Xcode 7.3.1) also utf16.count instead of utf16Count – Zaporozhchenko Oleksandr Sep 19 '16 at 10:45
  • Also I get 2 characters for this lady: using `.characters.count`. Looping over the characters, I get these: and – Jonny May 22 '17 at 10:49
97

Swift 1.2 Update: There's no longer a countElements for counting the size of collections. Just use the count function as a replacement: count("Swift")

Swift 2.0, 3.0 and 3.1:

let strLength = string.characters.count

Swift 4.2 (4.0 onwards): [Apple Documentation - Strings]

let strLength = string.count

San
  • 1,796
  • 13
  • 22
65

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)
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
whitneyland
  • 10,632
  • 9
  • 60
  • 68
  • 6
    Yes, we need an abstraction layer for Swift's syntax which is changing on a monthly basis! – Cosmin Jun 04 '16 at 14:35
  • @Lee This doesn't work in swift 4. as characters is deprecated. The whac-a-mole run around continues. sigh – Sentry.co Nov 09 '17 at 13:01
52

Swift 4

"string".count

;)

Swift 3

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

usage

"string".length

Vyacheslav
  • 26,359
  • 19
  • 112
  • 194
26

If you are just trying to see if a string is empty or not (checking for length of 0), Swift offers a simple boolean test method on String

myString.isEmpty

The other side of this coin was people asking in ObjectiveC how to ask if a string was empty where the answer was to check for a length of 0:

NSString is empty

Community
  • 1
  • 1
Kendall Helmstetter Gelner
  • 74,769
  • 26
  • 128
  • 150
23

Swift 5.1, 5

let flag = ""

print(flag.count)
// Prints "1" --  Counts the characters and emoji as length 1

print(flag.unicodeScalars.count)
// Prints "2" --  Counts the unicode lenght ex. "A" is 65

print(flag.utf16.count)
// Prints "4"

print(flag.utf8.count)
// Prints "8"
Saranjith
  • 11,242
  • 5
  • 69
  • 122
20

tl;dr If you want the length of a String type in terms of the number of human-readable characters, use countElements(). If you want to know the length in terms of the number of extended grapheme clusters, use endIndex. Read on for details.

The String type is implemented as an ordered collection (i.e., sequence) of Unicode characters, and it conforms to the CollectionType protocol, which conforms to the _CollectionType protocol, which is the input type expected by countElements(). Therefore, countElements() can be called, passing a String type, and it will return the count of characters.

However, in conforming to CollectionType, which in turn conforms to _CollectionType, String also implements the startIndex and endIndex computed properties, which actually represent the position of the index before the first character cluster, and position of the index after the last character cluster, respectively. So, in the string "ABC", the position of the index before A is 0 and after C is 3. Therefore, endIndex = 3, which is also the length of the string.

So, endIndex can be used to get the length of any String type, then, right?

Well, not always...Unicode characters are actually extended grapheme clusters, which are sequences of one or more Unicode scalars combined to create a single human-readable character.

let circledStar: Character = "\u{2606}\u{20DD}" // ☆⃝

circledStar is a single character made up of U+2606 (a white star), and U+20DD (a combining enclosing circle). Let's create a String from circledStar and compare the results of countElements() and endIndex.

let circledStarString = "\(circledStar)"
countElements(circledStarString) // 1
circledStarString.endIndex // 2
Forge
  • 6,538
  • 6
  • 44
  • 64
Scott Gardner
  • 8,603
  • 1
  • 44
  • 36
18

In Swift 2.0 count doesn't work anymore. You can use this instead:

var testString = "Scott"
var length = testString.characters.count
Aditya Srivastava
  • 2,630
  • 2
  • 13
  • 23
Antoine
  • 23,526
  • 11
  • 88
  • 94
16

Here's something shorter, and more natural than using a global function:

aString.utf16count

I don't know if it's available in beta 1, though. But it's definitely there in beta 2.

Jean Le Moignan
  • 22,158
  • 3
  • 31
  • 37
  • 2
    See Cezar’s answer. This will not necessarily give you the number of “characters” in the string, for most people’s definition of “character”. Then again, neither did Objective-C — it’s up to you to decide whether you care or not. – jbg Jul 19 '14 at 03:17
13

Updated for Xcode 6 beta 4, change method utf16count --> utf16Count

 var test1: String = "Scott"
 var length =  test1.utf16Count

Or

 var test1: String = "Scott"
 var length = test1.lengthOfBytesUsingEncoding(NSUTF16StringEncoding)
idmean
  • 14,540
  • 9
  • 54
  • 83
Kiet Nguyen
  • 609
  • 4
  • 8
12

As of Swift 1.2 utf16Count has been removed. You should now use the global count() function and pass the UTF16 view of the string. Example below...

let string = "Some string"
count(string.utf16)
Jeremy Fox
  • 2,668
  • 1
  • 25
  • 26
11

For Xcode 7.3 and Swift 2.2.

let str = ""
  1. If you want the number of visual characters:

    str.characters.count
    
  2. If you want the "16-bit code units within the string’s UTF-16 representation":

    str.utf16.count
    

Most of the time, 1 is what you need.

When would you need 2? I've found a use case for 2:

let regex = try! NSRegularExpression(pattern:"", 
    options: NSRegularExpressionOptions.UseUnixLineSeparators)
let str = ""
let result = regex.stringByReplacingMatchesInString(str, 
    options: NSMatchingOptions.WithTransparentBounds, 
    range: NSMakeRange(0, str.utf16.count), withTemplate: "dog")
print(result) // dogdogdogdogdogdog

If you use 1, the result is incorrect:

let result = regex.stringByReplacingMatchesInString(str, 
    options: NSMatchingOptions.WithTransparentBounds, 
    range: NSMakeRange(0, str.characters.count), withTemplate: "dog")
print(result) // dogdogdog
pkamb
  • 33,281
  • 23
  • 160
  • 191
Tyler Liu
  • 19,552
  • 11
  • 100
  • 84
9

You could try like this

var test1: String = "Scott"
var length =  test1.bridgeToObjectiveC().length
Forge
  • 6,538
  • 6
  • 44
  • 64
Anil Varghese
  • 42,757
  • 9
  • 93
  • 110
8

in Swift 2.x the following is how to find the length of a string

let findLength = "This is a string of text"
findLength.characters.count

returns 24

Adam
  • 373
  • 4
  • 13
7

Swift 2.0: Get a count: yourString.text.characters.count

Fun example of how this is useful would be to show a character countdown from some number (150 for example) in a UITextView:

func textViewDidChange(textView: UITextView) {
    yourStringLabel.text = String(150 - yourStringTextView.text.characters.count)
}
cjd
  • 101
  • 1
  • 2
6

In swift4 I have always used string.count till today I have found that

string.endIndex.encodedOffset

is the better substitution because it is faster - for 50 000 characters string is about 6 time faster than .count. The .count depends on the string length but .endIndex.encodedOffset doesn't.

But there is one NO. It is not good for strings with emojis, it will give wrong result, so only .count is correct.

VYT
  • 1,071
  • 19
  • 35
5

In Swift 4 : If the string does not contain unicode characters then use the following

let str : String = "abcd"
let count = str.count // output 4

If the string contains unicode chars then use the following :

let spain = "España"
let count1 = spain.count // output 6
let count2 = spain.utf8.count // output 7
Ashis Laha
  • 2,176
  • 3
  • 16
  • 17
  • Why would you want to use `utf8.count`? That doesn't give the count of characters. It gives the number of bytes needed for the UTF-8 encoding of the string. – rmaddy Jun 19 '19 at 21:38
4

In Xcode 6.1.1

extension String {    
    var length : Int { return self.utf16Count  }
}

I think that brainiacs will change this on every minor version.

Forge
  • 6,538
  • 6
  • 44
  • 64
user3812138
  • 261
  • 4
  • 11
4

Get string value from your textview or textfield:

let textlengthstring = (yourtextview?.text)! as String

Find the count of the characters in the string:

let numberOfChars = textlength.characters.count
Forge
  • 6,538
  • 6
  • 44
  • 64
kalyan711987
  • 476
  • 9
  • 14
4

Here is what I ended up doing

let replacementTextAsDecimal = Double(string)

if string.characters.count > 0 &&
    replacementTextAsDecimal == nil &&
    replacementTextHasDecimalSeparator == nil {
        return false
}
Shaishav Jogani
  • 2,111
  • 3
  • 23
  • 33
  • I think you are trying to do more than just getting the length of the string, and in any case this looks incomplete (shouldn't there also be a `return true` case?). Can you please double check and, in case, [edit] your answer? Thank you! – Fabio says Reinstate Monica Apr 25 '17 at 22:34
4

Swift 4 update comparing with swift 3

Swift 4 removes the need for a characters array on String. This means that you can directly call count on a string without getting characters array first.

"hello".count                  // 5

Whereas in swift 3, you will have to get characters array and then count element in that array. Note that this following method is still available in swift 4.0 as you can still call characters to access characters array of the given string

"hello".characters.count       // 5

Swift 4.0 also adopts Unicode 9 and it can now interprets grapheme clusters. For example, counting on an emoji will give you 1 while in swift 3.0, you may get counts greater than 1.

"".count // Swift 4.0 prints 1, Swift 3.0 prints 2
"‍❤️‍‍".count // Swift 4.0 prints 1, Swift 3.0 prints 4
Fangming
  • 24,551
  • 6
  • 100
  • 90
4

Swift 4

let str =  "Your name"

str.count 

Remember: Space is also counted in the number

Martin Evans
  • 45,791
  • 17
  • 81
  • 97
Mr.Shin
  • 89
  • 3
4

You can get the length simply by writing an extension:

extension String {
    // MARK: Use if it's Swift 2
    func stringLength(str: String) -> Int {
        return str.characters.count
    }

    // MARK: Use if it's Swift 3
    func stringLength(_ str: String) -> Int {
        return str.characters.count
    }

    // MARK: Use if it's Swift 4
    func stringLength(_ str: String) -> Int {
        return str.count
    }
}
Riajur Rahman
  • 1,976
  • 19
  • 28
3

Best way to count String in Swift is this:

var str = "Hello World"
var length = count(str.utf16)
Zaldy Bughaw
  • 797
  • 8
  • 16
2

String and NSString are toll free bridge so you can use all methods available to NSString with swift String

let x = "test" as NSString
let y : NSString = "string 2"
let lenx = x.count
let leny = y.count
Tien Dinh
  • 1,037
  • 7
  • 12
2
test1.characters.count

will get you the number of letters/numbers etc in your string.

ex:

test1 = "StackOverflow"

print(test1.characters.count)

(prints "13")

Andy Lebowitz
  • 1,471
  • 2
  • 16
  • 23
2

Apple made it different from other major language. The current way is to call:

test1.characters.count

However, to be careful, when you say length you mean the count of characters not the count of bytes, because those two can be different when you use non-ascii characters.

For example; "你好啊hi".characters.count will give you 5 but this is not the count of the bytes. To get the real count of bytes, you need to do "你好啊hi".lengthOfBytes(using: String.Encoding.utf8). This will give you 11.

Frank
  • 7,235
  • 9
  • 46
  • 56
2

Right now (in Swift 2.3) if you use:

myString.characters.count 

the method will return a "Distance" type, if you need the method to return an Integer you should type cast like so:

var count = myString.characters.count as Int
Jesse
  • 21
  • 2
2

my two cents for swift 3/4

If You need to conditionally compile

    #if swift(>=4.0)
            let len = text.count
        #else
            let len = text.characters.count
        #endif
ingconti
  • 10,876
  • 3
  • 61
  • 48
1
var str = "Hello, playground"
var newString = str as NSString    

countElements(str)

This counts the characters in Regular Swift String

countElements((newString as String))    

This counts the characters in a NSString

brokenrhino
  • 130
  • 2
  • 3
0

Using Xcode 6.4, Swift 1.2 and iOS 8.4:

    //: Playground - noun: a place where people can play

    import UIKit

    var str = "  He\u{2606}  "
    count(str) // 7

    let length = count(str.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())) as Int // 3
    println(length == 3) // true
King-Wizard
  • 15,628
  • 6
  • 82
  • 76
0

You can add this function to your extention

extension NSString { 
    func charLength() -> Int {
        return count(self as String)
    }
}
modusCell
  • 13,151
  • 9
  • 53
  • 80
Prakash Raj
  • 1,943
  • 1
  • 15
  • 13
0

You can use str.utf8.count and str.utf16.count which, I think, are the best solution

euvl
  • 4,716
  • 2
  • 25
  • 30
0

test1.endIndex gives the same result as test1.characters.count on Swift 3

Thracian
  • 43,021
  • 16
  • 133
  • 222
0

Universal Swift 4 and 3 solution

/**
 * Since swift 4 There is also native count, But it doesn't return Int
 * NOTE: was: var count:Int { return self.characters.count }
 * EXAMPLE: "abc".count//Output: 4
 */
extension String{
    var count:Int {
        return self.distance(from: self.startIndex, to: self.endIndex)
    }
}
Sentry.co
  • 5,355
  • 43
  • 38
0

In Swift 4.1 and Xcode 9.4.1

To get length in Objective c and Swift is different. In Obj-c we use length property, but in Swift we use count property

Example :

//In Swift
let stringLenght = "This is my String"
print(stringLenght.count)

//In Objective c
NSString * stringLenght = @"This is my String";
NSLog(@"%lu", stringLenght.length);
Naresh
  • 16,698
  • 6
  • 112
  • 113
0

In Swift 4.2 and Xcode 10.1

In Swift strings can be treated like an array of individual characters. So each character in string is like an element in array. To get the length of a string use yourStringName.count property.

In Swift

yourStringName.characters.count property in deprecated. So directly use strLength.count property.

let strLength = "This is my string"
print(strLength.count)
//print(strLength.characters.count) //Error: 'characters' is deprecated: Please use String or Substring directly

If Objective C

NSString *myString = @"Hello World";
NSLog(@"%lu", [myString length]); // 11
Naresh
  • 16,698
  • 6
  • 112
  • 113
0

Swift 5.0 strings can be treated as an array of individual characters. So, to return the length of a string you can use yourString.count to count the number of items in the characters array.

-1

If you are looking for a cleaner way to get length of a string checkout this library which has bunch of extensions to the Swift built in classes http://www.dollarswift.org/#length

Using this library you can just do "Some Str".length

Encore PTL
  • 8,084
  • 10
  • 43
  • 78
-1

You could use SwiftString (https://github.com/amayne/SwiftString) to do this.

"string".length // 6

DISCLAIMER: I wrote this extension

eurobrew
  • 77
  • 4