【发布时间】:2015-06-24 08:39:40
【问题描述】:
我有以下场景:
protocol A {}
protocol B: A {}
protocol C: A {}
let objects: [A] = ...
如何循环遍历数组并只为 B 类型的对象执行逻辑?
现在,我正在做这样的事情:
for object in objects {
if let b = object as? B {
...
}
}
但我想知道是否可以使用where 来使其更具表现力和优雅。
for b in objects where b is B // <- compiles, but b is typed as A, not B
for b: B in objects where b is B // <- doesn't compile
for b in objects as! [B] where b is B // <- I get a warning that "is" will always be true
【问题讨论】: