简体   繁体   中英

Swift - While Loops not functioning

I am trying to build a basic fibonacci sequence using a while loop in Swift.

The condition I am using in the while loop is while var next <= var maxNum, where next is an integer containing the newest element in the array to be appended, and maxNum is an integer that represents the largest element to be contained in the array (to test the while loop, I hardcoded it to ten).

Getting the following error when running the below code in playground: "Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)"

The while loop runs 90 times before this happens, letting me know that my condition is breaking down...var next should be greater than 10 after a few loops....not sure what's going on.

import UIKit

var myArray = [0,1]

var maxNum = 10
var next = 0

while next <= maxNum{
    var last = myArray.last!
    var lastLast = myArray[myArray.count-2]
    var next = last + lastLast
    myArray.append(next)
}


println(myArray)
println(myArray.last!)

The problem is that you are redeclaring next inside the body of your loop:

var next = last + lastLast

should be

next = last + lastLast

Once you make this correction, your code runs fine, producing the result below:

[0, 1, 1, 2, 3, 5, 8, 13]
13

Demo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM