【问题标题】:Swift: iterating through plistSwift:遍历 plist
【发布时间】:2014-07-13 21:59:52
【问题描述】:

我正在尝试使用 plist 来保存字典数组。一切似乎都很好,除了当我尝试遍历数组的每个元素时。在这种情况下,我使用 NSArrays 和 NSDictionarys。

在下面的示例中,albumInfoNSDictionary。键 "Title" 与字符串对象链接。我正在使用一种名为addAlbumInfo 的方法,它的参数都是Strings,除了"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"]
     );
  }

【问题讨论】:

    标签: ios nsarray swift nsdictionary plist


    【解决方案1】:

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

    albumInfo["title"] as String
    

    【讨论】:

    • 您可能必须先将其转换为任意对象。试试as AnyObject? as String
    • 这太奇怪了,但我会试试的
    • 还是不行。它说“NSString 不是 Int 的 sybtype”。不知道为什么提到 Int....
    • 你有 int 值而不是字符串吗?
    • albumInfo["price"] 应该返回一个数字
    【解决方案2】:

    我找到的解决方案是让 albumInfo 假设一个类型,然后键入每个值的大小写

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-29
      • 2021-03-01
      • 2015-08-26
      • 2016-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多