数组索引超出Swift中的Range

时间:2023-01-16 16:39:05

Hi i am trying to print elements of array in reverse order but i am getting error like

嗨,我试图以相反的顺序打印数组的元素,但我得到的错误就像

Array index out of Range.

数组索引超出范围。

Can u guys help me out? I am posting my code below

你们可以帮助我吗?我在下面发布我的代码

import UIKit

class DecimalToBinaryViewController: UIViewController {


@IBOutlet weak var textField: UITextField!

@IBOutlet weak var result: UILabel!


@IBAction func binaryNumber(sender: AnyObject)
{
    var myArray = [Int]()
     var number = textField.text.toInt()
    var num = Int(number!) // for converting optional Int? to Int
    var remainder:Int
   var condition = false
    while condition == false
    {
        remainder = num % 2
        myArray += [remainder]
        num /= 2
        if num == 0
        {
         condition = true
        }
    }
   var size = myArray.count
    for var i = size; i >= 0; i--
    {
     println( myArray[i])
    }


}

1 个解决方案

#1


0  

Arrays in swift are zero indexed. This means that when you have array count as X, the highest index you can access is X-1.

swift中的数组是零索引的。这意味着当数组计数为X时,您可以访问的最高索引是X-1。

You should make this change to your program

您应该对您的程序进行此更改

var size = myArray.count - 1

#1


0  

Arrays in swift are zero indexed. This means that when you have array count as X, the highest index you can access is X-1.

swift中的数组是零索引的。这意味着当数组计数为X时,您可以访问的最高索引是X-1。

You should make this change to your program

您应该对您的程序进行此更改

var size = myArray.count - 1