Ios 将swift迁移到swift 3 NSMUTABLEARRY
当我编写迁移swift代码时,我有一个错误“Type'Any'没有下标成员”,我的代码是Ios 将swift迁移到swift 3 NSMUTABLEARRY,ios,swift,swift3,Ios,Swift,Swift3,当我编写迁移swift代码时,我有一个错误“Type'Any'没有下标成员”,我的代码是 var myArray: NSMutableArray = [] func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{ let cell = UITableViewCell() if let name = self.myArray[(indexPath
var myArray: NSMutableArray = []
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = UITableViewCell()
if let name = self.myArray[(indexPath as NSIndexPath).row]["FirstName"] as? String{
cell.textLabel?.text = ("\(name)")
}
}
我尝试了很多方法,但是我没有这个问题的答案。你应该使用
- 仿制药
dequeueReusableCell
而不是indepath
nsindepath
import UIKit
class Controller: UITableViewController {
var persons = [[String:String]]()
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCell(withIdentifier: "MyCellID") ?? UITableViewCell(style: .default, reuseIdentifier: "MyCellID")
cell.textLabel?.text = persons[indexPath.row]["FirstName"]
return cell
}
}
首先:不要在Swift中使用
NSMutableArray
强>
发生此错误的原因是编译器需要知道对象是否可由键订阅。使用本机Swift类型可以解决这个问题
var myArray = [[String:Any]]()
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = UITableViewCell() // will not work
if let name = self.myArray[indexPath.row]["FirstName"] as? String { // optional binding actually not needed
cell.textLabel?.text = name // please no string interpolation
}
return cell // mandatory!
}
< >注意:<>代码> uITabeVIEW CELL()/<代码>将不起作用。建议使用可重复使用的单元
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
似乎您需要告诉编译器,
self.myArray[(indexath作为nsindexath.row]
是一个字典(并且允许使用[“FirstName”]
,访问键FirstName
)的值?不要使用NSMutableArray
。使用Swift数组。尝试var myArray:array?并将(indexPath作为NSIndexPath)。行
替换为indexPath.row
。使用Swift类型,而不是旧的Objective-C类型。请在发布前使用。此错误以前已被多次覆盖。此方法上的覆盖
仅适用于UITableViewController
。如果它是实现协议的另一种类,那么这里没有重写。此外,这与从Swift 1/2迁移到Swift 3无关。谢谢。这是结果:)