Reputation: 363
In this code, I am generating values for 2 different arrays. The value inside one array is dependant on the values inside the other array. The way it works is that in the array next_month_initial
, the value is dependant on the corresponding value in the water_deficit
array. However, the water_deficit
array value is dependant on the previous (not corresponding) value in the next_month_initial
array. Hence why the first value for the water_deficit array
is calculated independently, as no previous value exists in the next_month_initial
array. I hope this is clear enough to understand.
The code may be slightly confusing but content wise it is correct, the calculations are correct. There is no error message shown however the program is unable to correctly calculate all of the values in the array. When I print the array, instead of seeing an array with the correct values listed it says "Playground execution failed". I have no idea why this is happening, as i can see it this code should work.
var rainfall = [38,94,142,149,236,305,202,82,139,222,178,103]
let max_h2Ostore = 150
let carry_forward = 150
var evap_transpiration: [Int] = []
var water_deficit: [Int] = []
var next_month_initial: [Int] = []
// Generating values for water_deficit array
//The first values is generated differently to the remaining values
water_deficit[0] = rainfall[0] + carry_forward - evap_transpiration[0]
for i in 0...11 {
var x = i
if water_deficit[i] <= 0 {
next_month_initial.append(0)
} else if water_deficit[i] >= max_h2Ostore {
next_month_initial.append(max_h2Ostore)
} else {
next_month_initial.append(water_deficit[i])
}; if i != 11 {
x++
water_deficit.append(next_month_initial[i] + rainfall[x] - evap_transpiration[x])
}
}
println(water_deficit)
Upvotes: 0
Views: 338
Reputation: 14973
So to get your code to "work" you have to
Declare rainfall
(I guess you have it defined somewhere but it's not in your question) with 12 values:
let rainfall = [50, 13, 49, 30, 4, 5, 2, 9, 94, 48, 74, 39]
Declare evap_transpiration
with 12 values:
var evap_transpiration: [Int] = [30, 19, 59, 48, 39, 29, 49, 19, 49, 29, 49, 38]
Change the line before the loop to (You can't set the 0th element because there are none at that time):
water_deficit.append(rainfall[0] + carry_forward - evap_transpiration[0])
So your code works. I don't really know if it works correctly as I don't really know what you're trying to do, but at least it doesn't crash. If it does the thing you expect it to do (and it doesn't crash for you!) then I suggest posting your code on Code Review because this is some of the most horrible Swift code I have ever seen (sorry). I also recommend reading the The Swift Programming Language book from Apple, it's free and very easy to follow. (If you are posting it on Code Review then please add a good decription of what it does)
Upvotes: 1