Klas Zetterlund Klas Zetterlund - 1 month ago 27
Swift Question

Trying to get data from a number of consecutive dates

I'm trying to build an array of data from 3000 consecutive days but the code will only extract data from one single date 3000 times.
When I print the date that I keep increasing (

theincreasingnumberofdays
) I can see that it is adding one day to the date every time it loops, but when I read out the Array after the loop it's all the same data 3000 times.

class day
{
var week: Int?
var date: Int?
var month: Int?
var year: Int?
var weekday: Int?
}


@IBAction func pressbuttontodefinearray(sender: AnyObject) {
print("button has been pressed")

if (theArrayContainingAllTheUserData.count > 1) {
print("array contains something allready and we don't do anything")
return
}

print("array is empty and we're filling it right now")
var ScoopDay = day()

var numberofloops = 0

while theArrayContainingAllTheUserData.count < 3000
{
var theincreasingnumberofdays: NSDate {
return NSCalendar.current.date(byAdding: .day, value: numberofloops, to: NSDate() as Date)! as NSDate
}

print(theincreasingnumberofdays)

let myCalendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)!

// var thenextdate = calendar.date(byAdding: .day, value: numberofloops, to: date as Date)
numberofloops=numberofloops+1
ScoopDay.week=Int(myCalendar.component(.weekday, from: theincreasingnumberofdays as Date!))
ScoopDay.date=Int(myCalendar.component(.day, from: theincreasingnumberofdays as Date!))
ScoopDay.month=Int(myCalendar.component(.month, from: theincreasingnumberofdays as Date!))
ScoopDay.year=Int(myCalendar.component(.year, from: theincreasingnumberofdays as Date!))
ScoopDay.weekday=Int(myCalendar.component(.weekday, from: theincreasingnumberofdays as Date!))

theArrayContainingAllTheUserData.append(ScoopDay)
}

print("we're done with this looping business. Let's print it")
var placeinarray = 0
while placeinarray < 2998
{
print("Here is", placeinarray, theArrayContainingAllTheUserData[placeinarray].date, theArrayContainingAllTheUserData[placeinarray].month)
placeinarray=placeinarray+1
}

return
}

Answer

The problem is that there is one day object, named ScoopDay, and you are adding that one object to the array 3000 times. So the array ends up with 3000 references to that one single object, which contains the last values you assigned to it.

You can fix this by moving the line

var ScoopDay =  day()

inside the loop. That way you will create 3000 different day objects, each with different contents.

A Swift style tip: capitalize the first letter of class names, and lowercase the first letter of variable names, so:

class Day

and

var scoopDay =  Day()