Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the length of a String in Swift3 on macOS [duplicate]

How do I get the length of a String in 'Swift3' on macOS?

This used to work in Swift2:

if purchaseDateString.length == 0 {
     purchaseDateString = "n/a"
}

What is Swift3 equivalent for finding String's length.

UPDATE

There are answers to this question as Martin points out. The referred question has 30 answers. However, as far as I can tell, none of them relate specifically to Swift3. I could be wrong..

like image 824
ICL1901 Avatar asked Sep 01 '16 09:09

ICL1901


People also ask

How do I find the length of a string in Swift 5?

Swift – String Length/Count To get the length of a String in Swift, use count property of the string. count property is an integer value representing the number of characters in this string.

How do you truncate a string in Swift?

string-truncate.swift Truncates the string to the specified length number of characters and appends an optional trailing string if longer. - Parameter trailing: A 'String' that will be appended after the truncation. - Returns: 'String' object. let str = "I might be just a little bit too long".

How do I get the first character of a string in Swift?

In Swift, the first property is used to return the first character of a string.


1 Answers

Have you try characters.count

if purchaseDateString.characters.count == 0 {
     purchaseDateString = "n/a"
}

Edit:- As of in Swift 3.2 and Swift 4 String is Collection type so you can directly use count property on String.

if purchaseDateString.count == 0 {
     purchaseDateString = "n/a"
}
like image 68
Nirav D Avatar answered Sep 22 '22 04:09

Nirav D