简体   繁体   中英

How do I access an array and it objects within a plist with SWIFT?

Good Morning,

I have looked around here and Google but cant seem to find an answer. I have a plist called SoundsList - at the root level its a dictionary (default), the first item is an Array called Sounds and then its items are all strings.

I want to be able to access the items within the array but cant seem to find how to do this.

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

The above code is what I managed to find so far that gives me the path and the dictionary part - I managed to find this code within another post - Swift - Read plist

Regards,

Dave

Yes you are correct

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

this code gives you dictionary.You can print the contents of dictionary

println(dict)

As you described the structure of dictinary it should be like that

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

}

So to acess the soundlist you can use

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

You can iterate to each object by using

for item in soundsList {
   println(item)  //print sound1 and sound2
}

You should refer collection types from swift guide https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM