尝试从多个连续日期获取数据

Trying to get data from a number of consecutive dates

我试图构建一个连续 3000 天的数据数组,但代码只会从一个日期中提取数据 3000 次。 当我打印不断增加的日期(theincreasingnumberofdays)时,我可以看到它每次循环时都会在日期上增加一天,但是当我在循环后读出数组时,它都是相同的数据 3000 次.

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
}

问题是有一个 day 对象,名为 ScoopDay,而您将该对象添加到数组中 3000 次。因此,该数组最终包含对该单个对象的 3000 个引用,其中包含您分配给它的最后一个值。

您可以通过移动行

来解决这个问题
var ScoopDay =  day()

在循环内。这样您将创建 3000 个不同的 day 对象,每个对象都有不同的内容。

一个Swift风格提示:class名字首字母大写,变量名首字母小写,所以:

class Day

var scoopDay =  Day()