2016-04-30 66 views
1

我是Swift新手,无法检索plist中的信息(请参阅图像),特别是在迭代内容和比较plist与用户输入方面。我有一个Swift:使用for循环从plist中检索数据

“类型 '串' 不符合协议在我的代码 '序列类型'

错误。

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 
       } 
      } 
     } 

    } 
} 

Code

Plist

+0

不要将代码发布为图像,将实际文本放回原位,对于plist也是如此 – rmaddy

+0

阅读错误。 'locals'是一个'String',但你试图像数组一样迭代它。 – rmaddy

回答

2

你在告诉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数据或更改代码。你喜欢哪一个?

+0

谢谢,工作!我现在收到一个错误“无法在任何地方尝试访问本地值,例如local [”City“],local [”Preference“],而不能使用'String'类型的索引来下标'String'类型的值。 ]。你知道我怎样才能访问plist吗? – leisdorf

+0

'local'是一个数组,而不是一个字典。你可以用一个整数索引来访问一个值,例如'local [3]' – milesper

+0

你看我的plist数据如果您想使用该代码访问它,则结构错误。 – ryantxr

-1

您需要定义您所期望的类型。

它看起来像你期待locals是字典(无论是[String: String][String: AnyObject]数组,所以尽量铸造map["Local"]到(即[[String: String]])。

最后一个的plist是序列化结构化数据的方式。你需要了解你正在处理的结构,然后才能开始工作,然后才能开始工作。