ios - Subscript Swift iOS 的使用不明确

标签 ios swift swift2

自从更新最新的 Xcode 以来,我开始出现与这段代码相关的“Ambigously use of Subscript”错误;

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCellWithIdentifier("postsCell") as! CustomTableViewCell!
        if cell == nil {
            cell = CustomTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "postsCell")
        }
        let dict:NSDictionary = arrPosts[indexPath.row]

        if let postResourceName = dict["resource_name"]![0] as! String? where !postResourceName.isEmpty {
            cell?.customPostTitle?.text = String(htmlEncodedString: postResourceName)
        } else if let postTitle = dict["title"]!["rendered"] as? String {
            cell?.customPostTitle?.text = String(htmlEncodedString: postTitle)
        }

特别是在这一行;

if let postResourceName = dict["resource_name"]![0] as! String? where !postResourceName.isEmpty {

我对 Swift 还很陌生,我相信这与变量类型缺乏细节有关,这就是抛出错误的原因。但我不确定代码应该是什么。

有什么指点吗?

问候, 迈克尔

最佳答案

Swift 编译器会给你这个错误,因为它不知道你的字典中有哪些对象作为 value ,所以当你执行 dict["resource_name"]![0] 您想要将字典中包含的数组的第一项作为 进行访问。但您永远不会告诉您的值是数组,因此 values 的类型是 AnyObject。您可以通过替换来指定字典中有 Array

let dict:NSDictionary = arrPosts[indexPath.row]

let dict = arrPosts[indexPath.row] as [String:[String]]

关于ios - Subscript Swift iOS 的使用不明确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36223219/

相关文章:

ios - 具有不同数量项目的 CollectionView,项目应填充 Collection View

ios - 如何转换Class类型?

ios - 负字符串做小数 nsnumber

ios - 如何在 *.framework 包中省略或签署未签名的文件

swift - 使用 6 位 block 的更好方法

ios - Storyboard身份检查器中未显示自定义类

ios - SWIFT:快速点击 UIButton 会导致选票计数不正确

objective-c - 返回类型应该是什么?

swift - 试试!并尝试?有什么区别,什么时候使用它们?

ios swift datepicker完成按钮,错误的日期与间隔