0

I want to get the length of the text that is entered in a UISearchBar

I use the function that is called when the the searcbbar text starts editing.

func searchBarTextDidBeginEditing(searchBar: UISearchBar!) {
    println("EDITING")
    //TODO: Get length of text entered in searchBar
}

This doesn't work:

func searchBarTextDidBeginEditing(searchBar: UISearchBar!) {
    println("EDITING")
    //TODO: Get length of text entered in searchBar
    //Doesn't work. Error: String doesn't have a member named length
    searchBar.text.length
}

How can i retrieve the length of the entered text?

Ended up doing this:

searchBar.text.bridgeToObjectiveC().length
Binarian
  • 12,296
  • 8
  • 53
  • 84
Bas
  • 4,423
  • 8
  • 36
  • 53
  • 2
    See there http://stackoverflow.com/questions/24037711/get-the-length-of-a-string – mxb Jul 14 '14 at 15:04
  • @Bas, as you found a solution you can post it as the answer and accept, so question will have a resolution. If somebody finds a better way, I am sure they will provide their variant. – Keenle Jul 14 '14 at 18:17

1 Answers1

2

The problem is simply that the text property, like most objects arriving from the Cocoa API, might be nil. You have to assure Swift that it is not. Like this:

let len = countElements(searchBar.text!)
matt
  • 515,959
  • 87
  • 875
  • 1,141