菜鸟教程小白 发表于 2022-12-11 17:48:37

ios - 带有检查功能的数组超出范围


                                            <p><p>我有一个数组和一个检查函数。</p>

<p>点击按钮时的功能:</p>

<pre><code>// VARS
var workoutArray: !
var index = Int()

@IBAction func finishExerciseBtnPressed(_ sender: AnyObject) {

    // reload tabledata with next exercise in array

    print(&#34;the count of array is \(workoutArray.count)&#34;)

    if index &lt;= workoutArray.count {
      index = index + 1
      tableView.reloadData()
      print(&#34;The exercise number is \(index)&#34;)
    } else {
      // Show finish workout button
      print(&#34;No items found anymore&#34;)
    }
}
</code></pre>

<p><code>tableView</code> <code>dequeReusableCell</code>的功能:</p>

<pre><code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {
    if let cell = tableView.dequeueReusableCell(withIdentifier: &#34;workoutStartCell&#34;, for: indexPath) as? workoutStartCell {

      let workout = workoutArray
      cell.updateUI(workout: workout, exercise: index + 1)

      return cell

    }else{
      return UITableViewCell()
    }
}
</code></pre>

<p>我正在从以前的 <code>viewcontroller</code> 发送数字 0 到这个 vc 顶部的索引 var。我有检查方法 <code>finishExercisePressed</code> 但无论我在做什么,它都会一直计数低谷。它说索引超出范围,但我正在检查索引是否等于或低于数组的计数。</p>

<p>这是我想要达到的目标:</p>

<p> <a href="/image/lkcvX.png" rel="noreferrer noopener nofollow"><img src="/image/lkcvX.png" alt="enter image description here"/></a> </p>

<p>有人可以帮帮我吗?</p>

<p>非常感谢。 </p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><blockquote>
<p>I am checking if the index is equal or lower to the count of the arrays.</p>
</blockquote>

<p>没错。但是,您是在增加索引之前执行此操作,并且由于索引从零开始,您应该在结束前停止一个索引:</p>

<pre><code>var index = 1 // Set the index to 1 initially to skip the title
...
if index+1 &lt; workoutArray.count {
    index += 1
    tableView.reloadData()
    ...
}
</code></pre>

<p>上述检查验证 <code>index</code> 会在 <em></em> 递增后保持在范围内。</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 带有检查功能的数组超出范围,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/39961590/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/39961590/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 带有检查功能的数组超出范围