如何搜索结构 (Swift) [英] How to Search Struct (Swift)
问题描述
我正在更改我的 2 个数组...
I am changing my 2 arrays...
var title = ["Title 1", "Title 2", "Title 3"]
var artist = ["Artist 1", "Artist 2", "Artist 3"]
...到一个结构
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"),
]
我设置了我的 UITableView
以便单元格的标题等于 songs[indexPath.row].title
,单元格的副标题等于 songs[indexPath.row].artist
.
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
.
但是,我希望能够使用 UISearchBar
搜索 UITableView
.每当我只有变量而不是结构时,它就可以正常工作.但是,现在我发现了一个错误
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()
}
如您所见,在 filteredTitles = title.filter
行上,它调用了我的旧变量 title
.我应该用什么替换这一行,以便它搜索结构的标题?
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?
感谢您的帮助!
推荐答案
您需要将您的 filteredTitles
更改为 Song
的数组(并将其重命名为 过滤歌曲
.
You need to change your filteredTitles
to be an array of Song
(and rename it to filteredSongs
.
然后更新对 filter
的调用,以便将 text
替换为 song
并访问 title
属性歌曲
.
Then update the call to filter
such that text
is replaced with song
and you access the title
property of song
.
并且不需要将标题转换为 NSString
.
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()
}
这里假设 songs
是你的歌曲数组.
This assumes songs
is your array of songs.
请注意,还有很多其他清理工作.
Note there is a lot of other cleanup too.
你可能需要更新你的表视图数据源方法来处理 filteredSongs
是一个 Song
数组而不是一个 String
数组>.
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
.
这篇关于如何搜索结构 (Swift)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!