为什么由于索引超出范围而导致致命错误?

时间:2019-12-07 14:28:07

标签: swift xcode swift4

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)

当我尝试在快速代​​码上运行代码时,出现以下错误:致命错误:索引超出范围。 我正在尝试通过将数字数组中的每个元素本身相乘来复制double数组。

1 个答案:

答案 0 :(得分:1)

您的calculatedNumbers数组为空,并且您尝试在for循环中访问为空的calculatedNumbers [i]值。如果要在其中添加数据,请尝试以下方法:

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)