我是 Swift 的新手,在检索 plist 中的信息时遇到问题(参见图片),特别是在迭代内容并将 plist 与用户输入进行比较方面。我有一个
"Type 'String' does not conform to protocol 'Sequence Type'
我的代码有错误。
func matchTraveller(location: Destination, preference: TravellingPreference) -> String{
var message = ""
if let path = NSBundle.mainBundle().pathForResource("Locals", ofType: "plist"){
if let map = NSDictionary(contentsOfFile: path){
if let locals = map["Local"] as? String {
for local in locals{ // <-- ERROR HERE
let city = local["City"]
if local["City"] == location {
message = "We have matched you with \(local) in \(city)."
} else{
message = "Apologies, there aren't any locals registered in \(city) on LocalRetreat. Try again soon!"
break
}
if local["Preference"] == preference{
let prefer = local["Preference"]
message += "\(local) is also a \(prefer)"
}
return message
}
}
}
}
}
最佳答案
你告诉 Swift locals
是一个字符串。我认为您打算将其定义为 [String]
。
if let locals = map["Local"] as? String {
更改为:
if let locals = map["Local"] as? [String] {
您的 plist 数据与代码不匹配。您在 plist 中拥有的是字符串数组的字典。
[String: [String]]
代码试图将其作为字符串字典数组的字典进行访问:字符串。
[String: [String: String]]
您可以修改 plist 数据或更改代码。你想要哪一个?
关于ios - Swift:使用 for in 循环从 plist 中检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36961193/