【发布时间】:2015-06-17 20:51:25
【问题描述】:
我正在尝试从 plist 文件中迭代嵌套的 dict。问题在于分解内容时的类型不匹配。我总是收到错误,即 NSObject、NSDict 和其他 NSstuff 无法转换为字符串变量,包括当我使用“(值)”、字符串()作为 .. 如何将 plist dict 子集元组分解为单独的变量时?
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 并更新了代码,但类型不匹配仍然存在。正如 Airspeed Velocity 和 nhgrif 在 cmets 中指出的那样,更新 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")
}
}
顺便说一句,Airspeed Velocity,爱你的博客!
【问题讨论】: