swift 动态添加indexpath,数据类型出错怎么解决?

创建了一个可变数组,往数组里面插入相关节点的时候indexpath

报错信息为:cannot convert value of type 'NSMutalbeArray' to expected argument type '[IndexPath]'

//获取需要修正的indexpath

let indexPathArray = NSMutableArray()
    for i in startPosition...endPosition {
        let tempIndexPath:NSIndexPath = NSIndexPath(row: i, section: 0)
        indexPathArray.add(tempIndexPath)
    }
    //插入或者删除相关节点
    if expand {
        self.insertRows(at: indexPathArray, with: UITableViewRowAnimation.none)
    }
阅读 4k
2 个回答

insertRows(at: _, with: _) 这个方法,第一个参数,是一个 [IndexPath]
既然你用 swift,就推荐使用swift数据类型

这个[IndexPath] 也就是 Array<IndexPath>
Array 的定义是 swift 中的一个 struct
NSMutableArray 是一个 objc class ,与 struct 是完全不兼容的两个东西

我推荐的写法:

    var indexPathArray = [IndexPath]() // 看这里
    for i in startPosition...endPosition {
        let tempIndexPath = IndexPath(row: i, section: 0)
        indexPathArray.append(tempIndexPath) // 和这里
    }
    //插入或者删除相关节点
    if expand {
        self.insertRows(at: indexPathArray, with: .none)
    }
let indexPathArray: [IndexPath] = []

并且,在 Swift 3 中,移除了 NS 前缀,不要使用 NSIndexPath,而是用 IndexPath

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题