ios - Swift:遍历 plist

标签 ios nsarray swift nsdictionary plist

我正在尝试使用 plist 来保存字典数组。一切似乎都很好,除了当我尝试遍历数组的每个元素时。在本例中,我使用了 NSArrayNSDictionary

在下面的例子中,albumInfo 是一个 NSDictionary。键 "Title" 与字符串对象链接。我正在使用一个名为 addAlbumInfo 的方法,它的参数都是 String,除了 "price:"

请帮忙。

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

最佳答案

由于 albumInfo 是一个 NSDictionary,它只能包含 AnyObjects,这意味着它不能包含作为结构的 Swift 字符串。如果您的 addAlbumWithTitle 需要一个 String 并且您尝试将它传递给 AnyObject ,它将给您这个错误。您可以像这样将 albumInfo["title"] 转换为 Swift 字符串:

albumInfo["title"] as String

关于ios - Swift:遍历 plist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24727308/

相关文章:

ios - 导航自定义 titleView 不再仅在 iOS 11 上可见

ios - 如何在 Xcode 中隐藏警告

ios - 使用 NSUserDefaults 从 NSArray 中保存和检索 - Swift

swift - 如何正确实现导航器模式

android - Splash 流到 Container/FlatButton 之外 - Flutter

ios - 如何从 NSURLSessionDataTask 和调用 block 中获取返回值?

ios - 带有 NSDictionary、NSArray、JSON 和 HTML 数据的 NSPredicate

ios - 如何在iOS中对字典数组进行排序

ios - 使用 Swift 将照片上传到网络服务

ios - 项目在新的 XCode 6 中运行后出现 144 次致命故障