简体   繁体   中英

How to Search Struct (Swift)

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!

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM