I have created a function that performs summation of numbers, by accepting Int array and returning the sum of elements as integer value. Below is my code, which I checked to be logically correct, but I am getting error during runtime mentioning,'index out of range' in console and "
error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).
Code:
import UIKit
var x=[Int]()
var i=0
func dosomething(y:[Int])->Int{
for index in 0..<y.count{
if index==0{
x[index]=0
x[index]=x[index]+y[index]
i=x[index]
}
else{
x[index]=x[index-1]+y[index]
i=x[index]
}
}
return i
}
dosomething(y:[1,2,3])
reduce
func as shown in the first answer. I also would recommend to use proper variable names, becausevar555
andvar55
are very confusing.var555
??var555
.var555[index2]=0
— is invalid code.