Search code examples
iosnsarrayswiftnsdictionaryplist

Swift: iterating through plist


I am trying to use a plist to hold an array of dictionaries. Everything seems to be ok except for when I try to iterate through each element of the array. In this case I an using NSArrays and NSDictionarys.

In the below example, albumInfo is a NSDictionary. The key, "Title" is linked with the a string object. I am using a method called addAlbumInfo which has arguments which are all Strings except for the "price:"

Please help.

 var pathToAlbumsPlist:NSString = NSBundle.mainBundle().pathForResource("AlbumArray", ofType: "plist");
 var defaultAlbumPlist:NSArray = NSArray(contentsOfFile: pathToAlbumsPlist);

 for albumInfo:NSDictionary in defaultAlbumPlist {
     self.addAlbumWithTitle(
         albumInfo["title"],  //Says it is not convertable to a string
         artist: albumInfo["artist"],
         summary: albumInfo["summary"],
         price: albumInfo["price"].floatValue,
         locationInStore: albumInfo["locationInStore"]
     );
  }

Solution

  • the solution I found was to make albumInfo assume a type and then type case each of the values

    var pathToAlbumsPlist:NSString = NSBundle.mainBundle().pathForResource("AlbumArray", ofType: "plist");
    var defaultAlbumPlist:NSArray = NSArray(contentsOfFile: pathToAlbumsPlist);
    
    for albumInfo in defaultAlbumPlist {
        self.addAlbumWithTitle(albumInfo["title"] as String,
                        artist:albumInfo["artist"] as String,
                       summary:albumInfo["summary"] as String,
                         price:albumInfo["price"] as Float,
               locationInStore:albumInfo["locationInStore"] as String
        );
    }