Derek
Derek

Reputation: 2112

Swift compiler struggles with this expression

EDIT

The source of the issue seems to be the use of .lowercased() to return a lower case string. Adding this to any line seems to result in a 40-60ms compile time.


In an effort to speed up my compile times I've added the "-Xfrontend -debug-time-function-bodies" flag detailed here as well as following the optimisation tips here

The compiler seems to struggle with filter functions for example this:

    // Filter by search term
    if self.searchController.isActive {
        filteredManualTasksArray = self.filteredManualTasksArray.filter() {
            let taskName:String = $0.bmTaskName!.lowercased()
            let searchText:String = searchController.searchBar.text!.lowercased()
            return taskName.contains(searchText)
        }
    }

Result in this warning:

Expression took 51ms to type-check (limit: 50ms)

The variable filteredManualTasksArray is declared elsewhere as:

var filteredManualTasksArray:[BMTask]!

So all variables are explicitly typed as far as I can tell. Is there anything I can do to speed this up?

Edit: I've tried a couple of approaches that seem to make no difference

1) combining the three lines into one:

return $0.bmTaskName!.lowercased().contains(searchController.searchBar.text!.lowercased())

2) Specifying the filter type:

filteredManualTasksArray = self.filteredManualTasksArray.filter { (task: BMTask) -> Bool in

Edit 2

This line:

let searchText:String = searchController.searchBar.text!.lowercased()

Seems to be the cause of the issue - it take 38ms to type check. Any ideas how I can improve this?

Upvotes: 1

Views: 765

Answers (1)

Tom E
Tom E

Reputation: 1607

You could move the let searchText line out of the filter function:

if self.searchController.isActive {
    let searchText:String = searchController.searchBar.text!.lowercased()
    filteredManualTasksArray = self.filteredManualTasksArray.filter() {
        let taskName:String = $0.bmTaskName!.lowercased()
        return taskName.contains(searchText)
    }
}

Upvotes: 2

Related Questions