user3608914
user3608914

Reputation: 136

Puzzled with Closure Parameter in Swift

sorry for the novice question, but i really do not understand

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    if searchText.characters.count == 0{
        searchActive = false
        tableView.reloadData()
        return
    }

    searchActive = true
    filteredTableData = tableData.filter({( spaTown: String) -> Bool in
        let rangeTupple = (spaTown.startIndex, spaTown.endIndex)
        let spaRange = Range(uncheckedBounds: rangeTupple)
        let stringMatch = spaTown.range(of: searchText, options: String.CompareOptions.caseInsensitive, range: spaRange, locale: NSLocale.autoupdatingCurrent)
        return stringMatch != nil
    })

    tableView.reloadData()

}

The part i do not understand is the

filteredTableData = tableData.filter({( spaTown: String) -> Bool in

I don't understand how the function knows that spaTown string is the string that i wish to search through? Isn't it some arbitrary parameter name?

It puzzles me a lot..

Upvotes: 1

Views: 84

Answers (1)

DavidA
DavidA

Reputation: 3172

The system knows the type of the closure it's expecting as the argument to filter - it's expecting (Element)->Bool where Element is the type of the array elements.

When your code says {( spaTown: String) -> Bool in you're defining the closure that you're passing to it. You can use any name you like for the String variable - you chose spaTown. This is exactly like the parameters of a function: func f(spaTown:String)->Bool { ... } As long as the types match, the compiler is happy.

Upvotes: 1

Related Questions