自从更新最新的 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/