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.
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.
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
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
String and NSString are toll free bridge so you can use all methods available to NSString with swift String
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.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 stringSwift 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.
in Swift 2.x the following is how to find the length of a string
returns 24
Here is what I ended up doing
For XCode 7.3 and Swift 2.2.