Denis Rasulev
Denis Rasulev

Reputation: 4069

Error summing up the array values in Swift

I am new to Swift. Trying this code in Playground and get the error (see description below) Can you, please, point me to the right direction - where to look for the solution? Thanks in advance.

func randomSet(num: Int, max: Int) -> Array<Double> {

    var randArray = Array<Double>()

    for index in 0...num {
        randArray[index] = Double(arc4random_uniform(max+1))
    }

ERROR: var sum = randArray.reduce(0) {$0 + $1}

    for index in 0...num {
        randArray[index] = randArray[index] / Double(sum) * Double(max)
    }

    return randArray
}

test = randomSet(10, 100)

On the line marked with word ERROR, I get this:

Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

Upvotes: 0

Views: 94

Answers (2)

HamzaGhazouani
HamzaGhazouani

Reputation: 6614

The bug is not from the function reduce, but in initialization of your array, you can't access to index before initialization. The code below fix the bug.

  for index in 0...num {
    randArray.append(Double(arc4random_uniform(max+1)))
  }

Hope that helps

Upvotes: 1

mattt
mattt

Reputation: 19544

The error is actually caused by attempting to append values in randArray using subscripting. You should use append instead:

for _ in 0...num {
    randArray.append(Double(arc4random_uniform(max+1)))
}

Upvotes: 1

Related Questions