0

Something that has been driving me crazy is finding a simple thing: String length in Swift.

No, you cannot use string.length

No, you cannot use string.characters.count

No, you cannot use string.count

The only thing that works for me is string.endIndex. That however does not work for a simple textField check, e.g.

func textViewDidChange(textView: UITextView) {
    if textView.text.endIndex > 20 {
        setBorder(descriptionField, finished: true)
    } else {
        setBorder(descriptionField, finished: false)
    }
}

Since endIndex is not an Int and cannot be converted into in. This whole thing is driving me crazy, I don't know what to do. Any help would be appreciated!

pkamb
  • 33,281
  • 23
  • 160
  • 191
Julius
  • 1,451
  • 1
  • 15
  • 19

3 Answers3

5

Just use count()

count(textView.text)

in swift 2.0 some of the stuff you mentioned works =]

Chris Slowik
  • 2,859
  • 1
  • 14
  • 27
4

Apple have changed how to handle this this a few times which will make a lot of existing documentation out of date.

If you're using Swift 2 and above, use -

textView.text.characters.count

If you're using Swift 1.2, it's -

count(textView.text)

Jarrod Robins
  • 1,866
  • 2
  • 17
  • 23
0

In Swift 2.0, it is string.characters.count

Shripada
  • 6,296
  • 1
  • 30
  • 30