ios - 在 Swift 中访问 plist(错误 : "Expressions are not allowed at the top level")

标签 ios xcode swift ios8

我有一个 plist,我想在 Xcode 中将其作为 Swift 字典访问。我可以将文件的内容定义为 NSDictionary,但每次我尝试从中访问特定值/对象时,它都会显示错误“顶层不允许表达式”。我尝试过括号表示法、类型转换和使用自动完成的类方法(带点表示法)。

我的 plist 包含字典,其中包含包含 CGFloats 和字符串的字典。

我想访问实例的值。

这是我用来定义它的代码,它位于我的 GameScene.swift(这是一个 SpriteKit 游戏)的开头:

let levelBlocks = NSDictionary(contentsOfFile: NSBundle.mainBundle().pathForResource("LevelBlocks", ofType: "plist"))

我希望能够做到:

levelBlocks["Level1"]

编辑:添加更多信息。

我还尝试将其放入 ViewDidLoad()、init() 中,并使用符合函数内部 Hashable 的泛型而不是 AnyObject/Any。我仍然无法访问该字符串。

编辑2:我在ViewDidLoad()中尝试过这个,它返回错误254:

let levelBlocks = NSDictionary(contentsOfFile: NSBundle.mainBundle().pathForResource("LevelBlocks", ofType: "plist")) as Dictionary<String, Dictionary<String, Dictionary<String, String>>>
let test = levelBlocks["Level1"] as Dictionary<String, Dictionary<String, String>>
let test1 = test["Block0"] as Dictionary<String, String>
let test2 = test1["color"] as String
println(test2)

最佳答案

这是我找到的解决方案:

let levelBlocks = NSDictionary(contentsOfFile: NSBundle.mainBundle().pathForResource("LevelBlocks", ofType: "plist"))
let test: AnyObject = levelBlocks.objectForKey("Level1")
println(test) // Prints the value of test

我将 test 的类型设置为 AnyObject,以消除有关可能发生的意外推断的警告。

此外,它必须在类方法中完成。

访问并保存已知类型的特定值:

let value = levelBlocks.objectForKey("Level1").objectForKey("amount") as Int
println(toString(value)) // Converts value to String and prints it

关于ios - 在 Swift 中访问 plist(错误 : "Expressions are not allowed at the top level"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24335136/

相关文章:

ios - 更新后 iPhone 应用程序以 iPhone 4 大小运行,带有黑条

html - iOS:解析 HTML 并从中创建属性字符串和链接的最佳方法?

ios - 线程 1 : break point error to send post method

iphone - 如何使用 MKStoreKit 恢复购买

ios - UICollectionView : can't set value 内的 UITableView

ios - 点击图像时如何禁用 phonegap/cordova 上的图像缩放?

iphone - NSDateFormatter 语言环境

ios - 使用系统字体创建 SKLabelNode(UIFont 到字体名称)

ios - viewWillAppear 在 cellForItemAtIndexPath 之后调用?

iOS Storyboard - 自动布局不会调整 subview 的大小和位置