2017-03-14 114 views
-3

我有点困惑。我在Objective-C中有这个代码,我需要在swift中进行转换(得到相同的结果)。例如:For循环等效Swift 3

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

这个问题的答案实际上是遍布互联网......这是一个链接到苹果文档,所以你不必自己google:https://developer.apple.com/library/content/documentation/Swift/概念/ Swift_Programming_Language/ControlFlow.html – katzenhut

回答

1

尝试:

for cell in cells { 
    if let classCell = cell as? SomeTableViewCellClass { 
     classCell.doSomething() 
     // some coding 
    } 
} 
+0

感谢您的快速回答。我相信Eendje的答案也会这样做,但你的答案对我来说更容易理解。效果很好,非常感谢。 –

3

visibleCells返回UITableViewCell元件的阵列。 在Objective-C,你可以写

for (SomeTableViewCellClass *someCell in cells) { 
    // Do something with `someCell` ... 

} 

告诉编译器:“我知道所有的数组元素是 实际上是SomeTableViewCellClass实例只要相信我。”

这句法不会斯威夫特存在,类似的东西将是一个被迫投:

for someCell in someTableView.visibleCells as! [SomeTableViewCellClass] { 
    // Do something with `someCell` ... 

} 

,如果你错了无论是Objective-C和雨燕的代码将崩溃, 也就是说,如果一些小区不SomeTableViewCellClass的实例。

一个更安全的解决方案是一个用于环带的情况下的模式:

for case let someCell as SomeTableViewCellClass in someTableView.visibleCells { 
    // Do something with `someCell` ... 

} 

此列举它们是SomeTableViewCellClass子类的实例中的所有阵列元素,并跳过其他元素。

+1

这是很好的功能。不知道。谢谢。 –