我是新來的Swift和實驗。嘗試創建一個簡單的字典值數組。這很簡單,但我簡單地爲字典對象複製了一小段代碼,更改了每個部分中的值,然後將這四部分中的每一個添加到數組中。爲什麼在將字典添加到數組時添加
當我打印數組時,我發現它包含最後一個字典對象的四個版本。怎麼可能?我會期望該數組有四個字典對象,即添加每個對象之一。
func countDown() {
let dict: NSMutableDictionary = [:]
let enduroArrayFile = NSMutableArray()
dict.setObject(1, forKey: "SectionDistance")
dict.setObject("S", forKey: "Direction")
dict.setObject(0, forKey: "ArrivalTime")
dict.setObject(0, forKey: "AverageSpeed")
//saving dictionary to array
enduroArrayFile.addObject(dict)
dict.setObject(1.2, forKey: "SectionDistance")
dict.setObject("S", forKey: "Direction")
dict.setObject(0, forKey: "ArrivalTime")
dict.setObject(0, forKey: "AverageSpeed")
//saving dictionary to array
enduroArrayFile.addObject(dict)
dict.setObject(2, forKey: "SectionDistance")
dict.setObject("R", forKey: "Direction")
dict.setObject(0, forKey: "ArrivalTime")
dict.setObject(0, forKey: "AverageSpeed")
//saving dictionary to array
enduroArrayFile.addObject(dict)
dict.setObject(2.1, forKey: "SectionDistance")
dict.setObject("S", forKey: "Direction")
dict.setObject(0, forKey: "ArrivalTime")
dict.setObject(0, forKey: "AverageSpeed")
//saving dictionary to array
enduroArrayFile.addObject(dict)
print (enduroArrayFile)
}
輸出是
(
{
ArrivalTime = 0;
AverageSpeed = 0;
Direction = S;
SectionDistance = "2.1";
},
{
ArrivalTime = 0;
AverageSpeed = 0;
Direction = S;
SectionDistance = "2.1";
},
{
ArrivalTime = 0;
AverageSpeed = 0;
Direction = S;
SectionDistance = "2.1";
},
{
ArrivalTime = 0;
AverageSpeed = 0;
Direction = S;
SectionDistance = "2.1";
}
)
因爲NSDictionary是*引用類型*。您可以使用4個引用來創建一個具有相同一對一字典的數組。 –
請考慮使用Swift值類型:Dictionary,Array,... –