如何使用SWIFT访问数组及其在plist中的对象?

时间:2014-07-20 08:52:11

标签: swift plist ios8

早上好,

我在这里和谷歌一起看了看但似乎无法找到答案。我有一个名为SoundsList的plist - 在根级别它是一个字典(默认),第一个项目是一个名为Sounds的数组,然后它的项目都是字符串。

我希望能够访问数组中的项目,但似乎无法找到如何执行此操作。

let path = NSBundle.mainBundle().pathForResource("SoundsList", ofType: "plist")
let dict = NSDictionary(contentsOfFile: path)

上面的代码是我迄今为止找到的代码,它为我提供了路径和字典部分 - 我设法在另一篇文章中找到了这段代码 - Swift - Read plist

此致

戴夫

1 个答案:

答案 0 :(得分:2)

是的,你是对的

//Gives path of plist
let path = NSBundle.mainBundle().pathForResource("SoundsList", ofType: "plist")
//you are intializing dictionary from plist
let dict = NSDictionary(contentsOfFile: path)

此代码为您提供字典。您可以打印字典的内容

println(dict)

正如你所描述的那样,dictinary的结构应该是那样的

{
 "Sounds":(
            "sound1",
             "sound2"
          )

}

所以要获得你可以使用的声音列表

  var soundsList = dict["Sounds"]
  println(soundList) //this will print your soundList

您可以使用

迭代到每个对象
for item in soundsList {
   println(item)  //print sound1 and sound2
}

您应该参考swift guide https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html

中的集合类型
相关问题