gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 12:38:22 29 4
gpt4 key购买 nike

我试图构建一个连续 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
}

最佳答案

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

你可以通过移动线来解决这个问题

var ScoopDay =  day()

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

一个Swift风格的小技巧:类名首字母大写,变量名首字母小写,所以:

class Day

var scoopDay =  Day()

关于swift - 尝试从多个连续日期获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40225977/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com