菜鸟教程小白 发表于 2022-12-11 18:18:06

ios - 过滤结构时出错


                                            <p><p>我正在尝试过滤我的结构:</p>

<pre><code>class Song: CustomStringConvertible {
    let title: String
    let artist: String

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

    var description: String {
      return &#34;\(title) \(artist)&#34;
    }
}

var songs = [
    Song(title: &#34;Song Title 3&#34;, artist: &#34;Song Author 3&#34;),
    Song(title: &#34;Song Title 2&#34;, artist: &#34;Song Author 2&#34;),
    Song(title: &#34;Song Title 1&#34;, artist: &#34;Song Author 1&#34;),
    Song(title: &#34;Song Title 0&#34;, artist: &#34;Song Author 1&#34;)
]
</code></pre>

<p>在 <code>UITableView</code> 上显示:</p>

<pre><code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {
    var cell: LibrarySongTableViewCell! = tableView.dequeueReusableCell(withIdentifier: &#34;Library Cell&#34;) as! LibrarySongTableViewCell

    cell.titleLabel = songs.title
    cell.artistLabel = songs.artist
}
</code></pre>

<p>像这样:</p>

<pre><code>var filteredArtist = songs.filter { song -&gt; Bool in
    return song.artist == &#34;Artist Name&#34;
}
</code></pre>

<p>但是,每当我将 <code>cellForRowAtindexPath</code> 更改为</p> 时,我都会收到错误 <code>Thread 1: EXC_BAD_INSTRUCTION</code>

<pre><code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {
    var cell : LibrarySongTableViewCell! = tableView.dequeueReusableCell(withIdentifier: &#34;Library Cell&#34;) as! LibrarySongTableViewCell

    cell.titleLabel = filteredArtist.title
    cell.artistLabel = filteredArtist.artist
}
</code></pre>

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

<pre><code>cell.titleLabel = filteredArtist.title
</code></pre></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>正如 <em>@Martin R</em> 在评论中所说,问题可能与您的表格的总行数有关。</p>

<p>尝试像这样编写更新 <code>tableView:tableView:numberOfRowsInSection</code> 方法</p>

<pre><code>override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {
    return filteredArtist.count
}
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 过滤结构时出错,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/45128927/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/45128927/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 过滤结构时出错