13

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..

Nirav D
  • 71,513
  • 12
  • 161
  • 183
ICL1901
  • 7,632
  • 14
  • 90
  • 138
  • What is the type of `purchaseDateString`? Option-click on it to find out. – vacawama Sep 01 '16 at 09:19
  • 5
    It is `string.characters.count` since Swift 2. Your above code does *not* work in Swift 2. – Martin R Sep 01 '16 at 09:20
  • 3
    Checking for an empty string can also be done with `if string.isEmpty { }`, in Swift 2 and 3. – Martin R Sep 01 '16 at 09:23
  • Re your edit: *"none of them relate specifically to Swift3"* – that's because your problem is not specifically to Swift 3. As I said, nothing changed between Swift 2 and 3 with respect to this question. All Swift 2 answers in that Q&A are still valid. – Martin R Sep 01 '16 at 11:40
  • 1
    ok. in fact though, my code was working up to and including Xcode 8, beta 5. Anyway, thanks for the help. – ICL1901 Sep 01 '16 at 16:35

1 Answers1

57

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"
}
Naveed Ahmad
  • 6,627
  • 2
  • 58
  • 83
Nirav D
  • 71,513
  • 12
  • 161
  • 183