OGeek|极客世界-中国程序员成长平台

标题: ios - 过滤结构时出错 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 18:18
标题: ios - 过滤结构时出错

我正在尝试过滤我的结构:

class Song: CustomStringConvertible {
    let title: String
    let artist: String

    init(title: String, artist: String) {
        self.title = title
        self.artist = artist
    }

    var description: String {
        return "\(title) \(artist)"
    }
}

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

UITableView 上显示:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell: LibrarySongTableViewCell! = tableView.dequeueReusableCell(withIdentifier: "Library Cell") as! LibrarySongTableViewCell

    cell.titleLabel = songs[indexPath.row].title
    cell.artistLabel = songs[indexPath.row].artist
}

像这样:

var filteredArtist = songs.filter { song -> Bool in
    return song.artist == "Artist Name"
}

但是,每当我将 cellForRowAtindexPath 更改为

时,我都会收到错误 Thread 1: EXC_BAD_INSTRUCTION
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell : LibrarySongTableViewCell! = tableView.dequeueReusableCell(withIdentifier: "Library Cell") as! LibrarySongTableViewCell

    cell.titleLabel = filteredArtist[indexPath.row].title
    cell.artistLabel = filteredArtist[indexPath.row].artist
}

我该如何解决这个问题?我在这一行得到错误:

cell.titleLabel = filteredArtist[indexPath.row].title



Best Answer-推荐答案


正如 @Martin R 在评论中所说,问题可能与您的表格的总行数有关。

尝试像这样编写更新 tableView:tableView:numberOfRowsInSection 方法

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return filteredArtist.count
} 

关于ios - 过滤结构时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45128927/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4