Search code examples
swiftaverage

Calculating Average by Using a Function


I am trying to write a function to calculate the average in a simple math app. I am not getting any errors at all, but the code output is not showing up in the right sidebar in my Xcode playground. It outputs the two zeros in my code and stops there. Any thoughts on what's wrong?

func averageOf(numbers: Int...) -> Float {
    var sum = 0
    var numberTotal = 0

    for number in numbers {
        sum += number
        numberTotal = numbers.count
    }

    return Float(sum / numberTotal)
}

averageOf()
averageOf(10, 56, 75, 90, 109)

Solution

  • When you call averageOf(), it seems to cause the playground to crash (division by zero, because numberTotal is 0). For instance, if you called it like this:

    averageOf(10, 56, 75, 90, 109)
    averageOf(10, 20, 30)
    averageOf()
    averageOf(10, 20, 30)
    

    you would get an output for the first two calls, but not for the second two.

    UPDATE 3 (credits to @wumm) If you clicked on any of variables on the right panels or opened an assistant editor , you would see the error (rather strange one, though):

    Playground execution failed: error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).
    The process has been left at the point where it was interrupted, use "thread return -x" to return to the state before expression evaluation.
    * thread #1: tid = 0x1c4a02, 0x000000010aff7e14, queue = 'com.apple.main-thread', stop reason = EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
      * frame #0: 0x000000010aff7e14
    

    The solution is to check numberTotal in the end. And, by the way, there is no need to assign it inside the loop :) Here is a fixed version:

    UPDATE: cheching numberTotal in the beginning is more reasonable indeed (credits to @kovpas): UPDATE 2: changed the return part. Credits to `@MartinR.

    func averageOf(numbers: Int...) -> Float {
        var numberTotal = numbers.count
        if numberTotal == 0 {
            return 0
        }
        var sum = 0
    
        for number in numbers {
            sum += number
        }
        return Float(sum)/Float(numberTotal)
    }
    
    averageOf(10, 56, 75, 90, 109)
    averageOf(10, 20, 30)
    averageOf()
    averageOf(10, 20, 30)