0

I am trying to create a function in Playground using Swift where a calculation is made several times, and then added to the total sum of calculations until the loop is over. Everything seems to be working, except that when I try to sum the every calculation to the last total, it just gives me the value of the calculation. Here is my code:

func Calc(diff: String, hsh: String, sperunit: Float, rate: Float, n: Int16, p: Float, length: Int16) -> Float {
    //Divisions per Year
    let a: Int16 = length/n
    let rem = length - (a*n)
    let spl = Calc(diff, hsh: hash, sperunit: sperunit, rate: rate)

    for var i = 0; i < Int(a) ; i++ { //also tried for i in i..<a
        var result: Float = 0
        let h = (spl * Float(n) / pow (p,Float(i))) //This gives me a correct result
        result += h //This gives me the same result from h

        finalResult = result
    }
    finalResult = finalResult + (Float(rem) * spl / pow (p,Float(a))) //This line is meant to get the result variable out of the loop and do an extra calculation outside of the loop
    print(finalResult)
    return finalResult
}

Am I doing something wrong?

1 Answer 1

2

Currently your variable result is scoped to the loop and does not exist outside of it. Additionally every run of the loop creates a new result variable, initialized with 0.

What you have to do is move the line var result: Float = 0 in front of the for loop:

var result: Float = 0
for var i = 0; i < Int(a) ; i++ {
    let h = (spl * Float(n) / pow (p,Float(i)))
    result += h

    finalResult = result
}

Additionally you can remove the repeated assignment of finalResult = result and just do it once after the loop is over.

You can probably remove the finalResult completely. Just write

var result: Float = 0
for var i = 0; i < Int(a) ; i++ { 
    let h = (spl * Float(n) / pow (p,Float(i)))
    result += h
}
result += (Float(rem) * spl / pow (p,Float(a)))
print(result)
return result
Sign up to request clarification or add additional context in comments.

2 Comments

Worked out perfectly! Thank you so much!!
@JacoboKoenig you are welcome, feel free to take advantage of your newly earned privilege of upvoting helpful answers :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.