我想從plist文件迭代嵌套的字典。問題在於分解內容時類型不匹配。我總是得到錯誤,NSObject,NSDict和其他NSstuff不能轉換爲字符串變量,包括當我使用「(價值)」,字符串(),作爲..如何分解一個plist字典sub set tuple?(array)into separate variables ?迭代.plist字典。類型不匹配
func LoadPlistContacts() {
let path = NSBundle.mainBundle().pathForResource("ContactList", ofType: "plist")
var AppContactsList = NSDictionary(contentsOfFile: path!)
ListKeys = sorted(AppContactsList!.allKeys as! [String])
for key in ListKeys {
var (AppPersonName, AppPersonSurname, AppPersonCompany, AppPersonPhone) = AppContactsList[key]
}
}
更新: 我已經改變了與字典,而不是數組的plist中和更新的代碼,但類型不匹配仍然存在。 As Airspeed Velocity and nhgrif在評論中指出,例子確實與更新的plist有關。如果具有註釋錯誤的行不能解決它,我應該嵌套循環嗎?謝謝。
var ListKeys: [String]!
var ListContacts: [String: String]!
func LoadPlistContacts() {
if let path = NSBundle.mainBundle().pathForResource("ContactList", ofType: "plist") {
var AppContactsList = NSDictionary(contentsOfFile: path)
ListKeys = sorted(AppContactsList!.allKeys as! [String])
ListContacts = sorted(AppContactsList!.allValues as [String:String]) { $0.0 < $1.0 }
// I get an error [AnyObject] is not convertible to '[String:String]'
for contact in ListContacts {
let name = contact["Forename"] ?? ""
let surname = contact["Surname"] ?? ""
let address = contact["Company"] ?? ""
let phone = contact["Phone"] ?? ""
}
}
else {
fatalError("Could not open Contacts plist")
}
}
順便說一句,空速速度,愛你的博客!
我正在研究一個答案,但你很好涵蓋了所有要點。只是要評論說,提問者的plist結構並不符合你的說法。它看起來更像這樣:http://i.imgur.com/W03yayM.png – nhgrif
啊,真的,好點。代碼應該很容易適應,否則將是一個更加混亂的例子。 –
排序封閉測試中的.0訪問器是什麼?爲什麼它是必需的? –