2015-01-05 37 views
0

我在Swift中的字典中遇到了一個很大的問題。我有一些自定義類:團隊,競爭統計團隊比賽符合協議哈希可衡量的Swift dictionary does not working

字典看起來像這樣: [Team: [Competition: Statistics]]

此外我有兩個「總體價值」:團隊競爭

當我做到以下幾點: println(dictionary[overallTeam]!)

它打印出的競爭和統計數據,你會期望的內存地址。但是,當我執行以下操作時: println(dictionary[overallTeam]![overallCompetition])

我得到nil作爲輸出。我完全想知道,因爲dictionary[overallTeam]!中只有1個密鑰,它與overallCompetition同名。這意味着等號==返回true和hashValue是相同的。

請幫忙,哪裏會是這個問題。

下面的代碼:

init()方法我做到以下幾點:

dictionary = [Team: [Competition: Statistics]]() 
dictionary[overallTeam] = [Competition: Statistics]() 
dictionary[overallTeam]![overallCompetition] = Statistics() 

打印的代碼是在啓動應用程序時調用的方法:

println(overallCompetition.name) //"overallCompetition" 
println(overallCompetition.hashValue) //some hashCode, e.g. 5 
for item in dictionary[overallTeam]!.keys { //executed once 
    println(item.name) //"overallCompetition" 
    println(item.hashValue) //SAME hashCode, e.g. 5 
    println(dictionary[overallTeam]![item]!.value) //prints the value expected 
} 
println(dictionary[overallTeam]) //prints some memory addresses 
println(dictionary[overallTeam]![overallCompetition]) //nil 
println(dictionary[overallTeam]![overallCompetition]!.value) //error: unexpectedly found nil 

剛一個普遍的問題:字典鍵是基於hashValue的,不是嗎?然後爲什麼做兩個鍵與相同 hashValue不會產生相同結果???

+1

請問您可以發佈設置和打印字典變量的代碼。 –

+0

您的詞典將內部詞典定義爲具有統計密鑰,但內部詞典使用PlayerStatistics鍵進行初始化,然後將該值初始化爲統計對象...是統計PlayerStatistics的子類或是PlayerStatistics統計的子類,因爲你的代碼暗示着兩者都是彼此的子類。將內部字典的值類型更改爲統計信息並查看是否有效。 – ad121

+0

哦,對不起,忘了改變它,改變了名字,以便它們在這裏不那麼久。 – borchero

回答

0

您不能將字符串與不同的對象類型進行比較並獲得一致的結果,因爲該關係不是自反的。換句話說,雖然你可能已經實現了Equatable來說你的對象==字符串,但並不是因此string ==對象,這會破壞它。

既然你是通過字符串名稱索引數組,那麼你永遠不會用overallCompetition找到它。將第二個字典存儲爲overallCompetition作爲值,或使用overallCompetition.name提取值。

+0

我沒有比較字符串與對象 - 只比較兩個對象的兩個字符串 – borchero

+0

您的代碼表明'overallCompetition'是一個對象類型,並且您發佈的代碼表明您的字典通過字符串存儲鍵。所以你的代碼或者需要在其查找中使用'overallCompetition.name',或者你需要將對象存儲爲關鍵字。 – AlBlue

+0

關鍵是外部字典中的Team對象和內部字段中的競爭對象 – borchero