Babylon
Babylon

Reputation: 21

why do i get fatal error because of Index out of range?

var numbers = [45, 73, 195, 53]

//Write your code here
 //Replace this comment with your code.
var computedNumbers : [Double] = Array() 
for i in 0...numbers.count-1 {computedNumbers[i] = Double(numbers[i])*Double(numbers[i])}
print(computedNumbers)

When I try to run the code on swift code it gives me the following error: Fatal error: Index out of range. I'm trying to reproduce an array of double by multiplying every element in numbers array by itself.

Upvotes: 1

Views: 79

Answers (1)

Keshu R.
Keshu R.

Reputation: 5223

your computedNumbers array is empty and you are trying to access computedNumbers[i] value in your for loop which is empty. if you want to add data in it, try this instead:

var numbers = [45, 73, 195, 53]

//Write your code here
 //Replace this comment with your code.
var computedNumbers : [Double] = []
for i in 0...numbers.count-1 {
  let num = Double(numbers[i])*Double(numbers[i])
  computedNumbers.append(num)
} 
print(computedNumbers)

Upvotes: 1

Related Questions