2017-02-14 74 views
1

我試圖元素添加到詞典中定義爲一個陣列內追加值到一個數組如下:試圖字典

var eventsByQuarter = Dictionary<Int, [D_MatchEvents]>() 

字典保持在體育比賽事件的細節,其中鍵是有關比賽的四分之一。即第1季度的每個事件都在分配給該詞典項目的數組中(我將稍後將該詞典用作包含4個部分的表格視圖的數據源)。

D_MatchEventsCore Data定義,並且與MatchData實體具有多對一的關係。每個事件的「季度」已被捕獲爲MatchEvents實體中的一個屬性。

func loadMatchEvents() { 
    match = DatabaseController.fetchMatch(matchUUID)! 
    matchEvents = match?.r_ToEvents?.allObjects as! [D_MatchEvents] 
    matchEvents = matchEvents.sorted() {($0.d_EventTimestamp?.compare($1.d_EventTimestamp as! Date) == .orderedAscending)} 

    for event in matchEvents { 
     eventsByQuarter[event.d_EventQuarter] = eventsByQuarter.append(event) 
    } 
} 

matchEvents正確加載D_MatchEvents類型的排序陣列,但是當我嘗試遍歷數組追加每個事件在詞典正確的「季度」數組我在嘗試引用時不明確的錯誤成員'下標'。

我看不出我能做到這一點。任何幫助,將不勝感激。

+0

是'int'類型的'd_EventQuarter'? – shallowThought

+0

實際上它是Int16類型?因爲核心數據不允許Int – Jonno

+0

我很緊張,但我認爲解開它會解決錯誤。 – shallowThought

回答

1

鑑於你解釋的結構,問題就在這裏:

for event in matchEvents { 
    eventsByQuarter[event.d_EventQuarter] = eventsByQuarter.append(event) 
} 

它應該是:

for event in matchEvents { 
    eventsByQuarter[event.d_EventQuarter]?.append(event) 
} 

雖然你真的需要檢查,看看是否有甚至的現有陣列給定的鍵,所以我會做這樣的事情:

for event in matchEvents { 
    //Create a variable that is either a mutable copy of the existing array, or a new, empty array of the correct type 
    var thisQuarter = eventsByQuarter[event.d_eventQuarter] ?? [D_MatchEvents]() 
    //Add the new item 
    thisQuarter.append(event) 
    //Replace the existing array with the appended copy, or add a new key-value pair (if it didn't already exist) 
    eventsByQuarter[event.d_eventQuarter] = thisQuarter 
} 

不是超高效,但它是一個快速實施

0

感謝您的支持。它讓我進一步尋找它。我現在已經找到了解決方案。事實上,我需要做的是將鍵定義爲自己的變量,而不是直接引用數組的元素。所以現在的代碼看起來像這樣

for event in matchEvents { 
     let qtr:Int = Int(event.d_EventQuarter) 
     eventsByQuarter[qtr]?.append(event) 
    } 

我不知道爲什麼會這樣,但它的工作原理。使用SWIFT仍然會發現許多謎題之一!關於在追加之前關於檢查字典項目是否存在的其他評論,我完全同意在其他情況下,但是在這裏,我知道總是有4個項目,不多不少,因此選擇了簡單地在開始時初始化它們,那麼不需要進一步的檢查。在循環數組來設置字典之前,我只是這樣做。

 for index in 1...4 { eventsByQuarter[index] = [] }