Swift:为什么在使用append时没有元素添加到我的数组?

时间:2018-01-10 19:59:22

标签: arrays swift

我想创建一个Fibonacci序列。用户将输入一个数字,例如9,然后将显示斐波纳契数列,以最近的斐波纳契数列结束。所以,在这种情况下:0,1,1,2,3,5,8

我在2D数组中存储元素时遇到问题。当循环从0开始时,存储0索引处的0,当循环变为1时,再次存储索引0处的1,但它应该存储在索引1处。这导致索引超出范围错误代码我应该使用与追加或其他不同的东西吗?

 func fabino(until: Int) {

    if until > 2 {
        for number in 0...until {

            var arrayOfDemoNumbers = [Int]()

            if number > 1 {
               arrayOfDemoNumbers.append(arrayOfDemoNumbers[number - 1] + arrayOfDemoNumbers[number - 2])
                listOfNumbers = listOfNumbers + "\(arrayOfDemoNumbers[number]), "
            }else{
                sum = number + sum
                arrayOfDemoNumbers.append(sum)
               // arrayOfDemoNumbers[number] = sum
                listOfNumbers = listOfNumbers + "\(sum), "
                dump(arrayOfDemoNumbers)
            }
        }}else{
            self.listOfNumbers = "0,1,1"
        }

        labelToChange.text = listOfNumbers

    }

1 个答案:

答案 0 :(得分:1)

 func fabino(until: Int) {
    var arrayOfDemoNumbers = [Int]()

    if until > 2 {
        for number in 0...until {

            if number > 1 {
               arrayOfDemoNumbers.append(arrayOfDemoNumbers[number - 1] + arrayOfDemoNumbers[number - 2])
                listOfNumbers = listOfNumbers + "\(arrayOfDemoNumbers[number]), "
            }else{
                sum = number + sum
                arrayOfDemoNumbers.append(sum)
               // arrayOfDemoNumbers[number] = sum
                listOfNumbers = listOfNumbers + "\(sum), "
                dump(arrayOfDemoNumbers)
            }
        }}else{
            self.listOfNumbers = "0,1,1"
        }

        labelToChange.text = listOfNumbers

    }