ios - Swift:使用 for in 循环从 plist 中检索数据

标签 ios swift plist

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

    }
}

Code

Plist

最佳答案

你告诉 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/

相关文章:

python - pliSTLib 无法读取 Safari 的 plist 文件

ios - Collection View 单元格内容未显示

ios - 使用 UIDocumentInteractionController 时点击 "Open in Instagram"时发生崩溃

ios - 什么可能导致调用工具包中的 CXErrorCodeRequestTransactionErrorUnentitled 错误?

ios - 有没有办法在 swift 4 中更改 UINavigationBar 的背景颜色

swift - 如何检测节点上的触摸

typescript 在 MacOS 上被错误识别为 MPEG 文件

iOS - 是否有任何框架可以以 plist 或 xml 的形式提供大量任意二进制数据?

objective-c - 在 Objective-c 中使用调度队列

ios - ScrollView 无法快速放大或缩小