DerrickHo328
DerrickHo328

Reputation: 4886

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"]
     );
  }

Upvotes: 0

Views: 2074

Answers (2)

DerrickHo328
DerrickHo328

Reputation: 4886

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
    );
}

Upvotes: 1

Connor
Connor

Reputation: 64644

Since albumInfo is an NSDictionary it can only contain AnyObjects, which means it can't contain a Swift String that is a struct. If your addAlbumWithTitle expects a String and you try to pass it an AnyObject it will give you this error. You can cast albumInfo["title"] to a Swift String like this:

albumInfo["title"] as String

Upvotes: 1

Related Questions