我试图从连续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
}
答案 0 :(得分:2)
问题是有一个名为day
的{{1}}对象,并且您将该对象添加到数组3000次。因此,数组最终会对该单个对象进行3000次引用,该对象包含您为其分配的最后一个值。
您可以通过移动线
来解决此问题ScoopDay
循环内部。这样,您将创建3000个不同的var ScoopDay = day()
个对象,每个对象具有不同的内容。
Swift样式提示:大写类名的第一个字母,并小写变量名的第一个字母,所以:
day
和
class Day