过滤结构时出错

时间:2017-07-16 13:05:29

标签: ios swift uitableview struct

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

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"
}

但是,每当我将Thread 1: EXC_BAD_INSTRUCTION更改为

时,我都会收到错误cellForRowAtindexPath
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

1 个答案:

答案 0 :(得分:0)

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

尝试编写更新tableView:tableView:numberOfRowsInSection方法,如下所示

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