我有点困惑。我在Objective-C中有这个代码,我需要在swift中转换(得到相同的结果)。例如:
NSArray *cells = [self.someTableView visibleCells];
for (SomeTableViewCellClass *someCell in cells){
// some coding
}
我尝试过这样,但它会抛出一个错误,表示someCell从未使用过,请考虑删除它:
for someCell in cells { // in this line
let comeCell = SomeTableViewCellClass
// some coding
}
但是,如果我这样做,它表示不能将值从一个转换为另一个:
for someCell in cells as SomeTableViewCellClass { // in this line
// some coding
}
我知道这里有一些关于这个问题的帖子,但是就像我读到的那样,它们有点不同,可以用我自己的代码nr.2来解决。我的Objective-C文件中有很多这样的循环,所以如果有人可以帮助我并回答是否有任何等价物,我将不胜感激?!
答案 0 :(得分:3)
visibleCells
返回UITableViewCell
元素数组。
在Objective-C中你可以写
for (SomeTableViewCellClass *someCell in cells) {
// Do something with `someCell` ...
}
告诉编译器:“我知道所有数组元素都是
实际上是SomeTableViewCellClass
的一个实例。只要相信我。“
Swift中不存在该语法,类似的东西将是强制转换:
for someCell in someTableView.visibleCells as! [SomeTableViewCellClass] {
// Do something with `someCell` ...
}
如果你错了,Objective-C和Swift代码都会崩溃
即,如果某个单元格不是SomeTableViewCellClass
的实例。
更安全的解决方案是带有案例模式的for循环:
for case let someCell as SomeTableViewCellClass in someTableView.visibleCells {
// Do something with `someCell` ...
}
这枚举所有数组元素,它们是SomeTableViewCellClass
子类的一个实例,并跳过其他元素。
答案 1 :(得分:1)
试试这个:
for cell in cells {
if let classCell = cell as? SomeTableViewCellClass {
classCell.doSomething()
// some coding
}
}