swiftuisearchbar

How to get length of text enter in search bar?


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

Solution

  • 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!)