我能把这个组合的for-plus-if压缩成一个for吗,
也就是说,我能把前两行合并成一个循环指令吗?
它应该只访问childNodes中作为MyNode实例的对象。
for childNode in childNodes {
if let myNode = childNode as? MyNode {
// do something with myNode
}
}发布于 2014-11-19 10:04:03
我假定childNodes是一个数组。如果是,那么您可以过滤它:
for childNode in (childNodes.filter { $0 is MyNode }) {
println ("It's a node")
}或者如果您更喜欢更显式的代码:
let nodes = childNodes.filter { $0 is MyNode }
for childNode in nodes {
println ("It's a node")
}据我所知,在斯威夫特中,没有干净的方法可以将for循环与可选绑定结合起来,以跳过一些迭代。
可以使用标准的for循环,结合给定索引的闭包返回包含MyNode实例的下一个索引.但我不认为它在代码和可读性方面是简化的:
let findNext = { (var index: Int) -> (node: MyNode?, next: Int) in
while index < childNodes.count {
if let node = childNodes[index] as? MyNode {
return (node, index)
}
++index
}
return (nil, index)
}
for var (node, index) = findNext(0); node != nil; (node, index) = findNext(index + 1) {
println ("it's a node: \(node!)")
}发布于 2014-11-19 10:47:25
尝试:
let nodes = childNodes.filter({ $0 is MyNode }).map({ $0 as MyNode }) // Array<MyNode>
for node in nodes {
...
}如果您不喜欢中间数组的创建,折叠就是解决方案,但可能比上面的要慢。
// ↓
let nodes = lazy(childNodes).filter({ $0 is MyNode }).map({ $0 as MyNode }) // nodes: LazySequence<MapSequenceView<FilterSequenceView<[Any]>, MyNode>>
for node in nodes {
...
}https://stackoverflow.com/questions/27013871
复制相似问题