【问题标题】:ambiguous reference to member subscript after conversion of code from swift 2 to swift 3 in xcode 8在xcode 8中将代码从swift 2转换为swift 3后对成员下标的模糊引用
【发布时间】:2018-03-07 09:33:56
【问题描述】:

我是快速编程的新手。将此代码从 swift 2 更新到 swift 3 后,我遇到了这个问题

Swift 2 代码是

let dicConversation = self.conversationListArray?[indexPath.row] as! NSMutableDictionary 

现在我在 swift 3 中成功地转换了这段代码,方法是把它分成几部分

Swift 3 代码

let accountArrayDict = self.conversationListArray?[indexPath.row] as? Dictionary<String, Any>
let accountArray : [String : String] = accountArrayDict?["accounts"] as! [String : String]

代码在 swift 3 中成功转换,但我不知道如何转换下面的这一行:

cell.conversationTitle?.text = accountArray?[0]["displayName"] as? String
        

这是我尝试过的,但在第一部分显示错误。第二个现在好了

cell.conversationTitle?.text = accountArray[0] as![String]
let accountArray : [String] = accountArrayDict?["displayName"] as! [String]

【问题讨论】:

  • 可以把self.conversationListArray的内容打印出来吗?
  • 尊敬的先生@MidhunMP 我可以打印出带有这些错误的conversationListArray 的内容,因为程序构建失败了吗?
  • 只需注释掉有问题的代码并仅打印该数据。我遇到了问题,但在发布答案之前,最好先看看你的数据结构

标签: ios arrays swift3 code-migration


【解决方案1】:

首先,从不将(非可选)表视图的数据源数组声明为可选。

var conversationListArray = [[String:Any]]()

这避免了很多问号和类型转换,
编译器知道accountArrayDict[String:Any]

let accountArrayDict = self.conversationListArray[indexPath.row]

名称accountArray 暗示该类型是一个数组,所以它是

let accountArray = accountArrayDict["accounts"] as! [[String : String]]

那你就可以写了

cell.conversationTitle?.text = accountArray[0]["displayName"]

由于编译器知道内部字典具有String 值,因此您也可以摆脱这种类型转换。这就是为什么 Swift 原生类型比 Foundation NS(Mutable)... 集合类型更高效的一个很好的例子。

尽管如此,对于这样的嵌套数据模型,强烈建议使用自定义结构或类。

【讨论】:

  • 非常感谢先生 :) 你是救世主再次感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-07
  • 2016-05-01
相关资源
最近更新 更多