2016-10-24 4 views
0

私は3000日連続してデータの配列を作成しようとしていますが、コードは1回の日付から3000回だけデータを抽出します。 増加し続ける日付(theincreasingnumberofdays)を印刷すると、ループするたびに日付に1日追加されることがわかりますが、ループの後に配列を読み出すと、すべて同じデータ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

サイドノートを:あなたのループは非常にあります高価な。たとえば、同じタイプの3000カレンダーインスタンスを作成していて、受信したコンポーネントはすべて「Int」です。 – vadian

答えて

2

問題がScoopDayという名前の1つのdayオブジェクトがあるということです、そしてあなたは、アレイ3000回に1つのオブジェクトを追加しています。配列は最後に指定した値を含む単一のオブジェクトへの3000の参照で終わります。

あなたがループ内でライン

var ScoopDay = day() 

を移動することでこの問題を解決することができます。そうすれば、それぞれ異なる内容の3000個の異なるdayオブジェクトを作成します。

スウィフトスタイルのヒント:ので、クラス名の最初の文字を大文字にし、変数名の最初の文字を小文字:

class Day 

var scoopDay = Day() 
+0

あなたは、神様です!ありがとうございました! –

+0

よろしくお願いします!それがあなたの質問に答えるなら、質問に答えた印を付けてください - ありがとう! –

関連する問題