0

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)

2
  • 3
    Please edit the title of your post to be more descriptive of the problem. How can I correct this? will be absolutely meaningless when it turns up in a search result by a future user here. Your title should describe the problem or contain a descriptive question that has some relevance. Thanks. Commented Feb 4, 2015 at 18:48
  • Note that 0...num includes the range end, so that will give you an array with num+1 elements. You probably want to 0 ..< num instead. Commented Feb 4, 2015 at 18:58

2 Answers 2

1

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)))
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Thank you, Hamza, that made even more clear! In other words, I have to populate my array with some values before I can use index. Got it.

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.