How to Search Struct (Swift)

你离开我真会死。 提交于 2019-12-23 04:35:57

问题


I am changing my 2 arrays...

var title = ["Title 1", "Title 2", "Title 3"]
var artist = ["Artist 1", "Artist 2", "Artist 3"]

...to a struct

struct Song {
    var title: String
    var artist: String
}

var songs: [Song] = [
    Song(title: "Title 1", artist "Artist 1"),
    Song(title: "Title 2", artist "Artist 2"),
    Song(title: "Title 3", artist "Artist 3"),
]

I set up my UITableView so that the title of the cell equals songs[indexPath.row].title, and the subtitle of the cell equals songs[indexPath.row].artist.

But, I want to be able to search the UITableView with a UISearchBar. Whenever I just had the variables and not the struct, it worked fine. But, now I am finding an error on

var filteredTitles:[String] = []
var searchActive : Bool = false

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

    filteredTitles = title.filter //the error ({ (text) -> Bool in
        let tmp: NSString = text as NSString
        let range = tmp.range(of: searchText, options: NSString.CompareOptions.caseInsensitive)
        return range.location != NSNotFound
    })
        if(filteredTitles.count == 0){
        searchActive = false;
    } else {
        searchActive = true;
    }
    self.myTableView.reloadData()
}

As you can see, on the line filteredTitles = title.filter it calls my old variable, title. What should I replace this line with so that it searches the struct's title?

Thanks for the help!


回答1:


You need to change your filteredTitles to be an array of Song (and rename it to filteredSongs.

Then update the call to filter such that text is replaced with song and you access the title property of song.

And there is no need to cast the title to NSString.

Here's your code with the needed changes:

var filteredSongs = [Song]()
var searchActive = false

func searchBar(searchText: String) {
    filteredSongs = songs.filter { (song) -> Bool in
        return song.title.range(of: searchText, options: [ .caseInsensitive ]) != nil
    }

    searchActive = !filteredSongs.isEmpty

    self.myTableView.reloadData()
}

This assumes songs is your array of songs.

Note there is a lot of other cleanup too.

And you probably need to update your table view data source methods to deal with filteredSongs being an array of Song instead of an array of String.



来源:https://stackoverflow.com/questions/44875057/how-to-search-struct-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!