我有以下场景:
protocol A {}
protocol B: A {}
protocol C: A {}
let objects: [A] = ...
Run Code Online (Sandbox Code Playgroud)
我如何遍历数组并仅执行类型对象的逻辑B?
现在,我正在做这样的事情:
for object in objects {
if let b = object as? B {
...
}
}
Run Code Online (Sandbox Code Playgroud)
但我想知道我是否可以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
Run Code Online (Sandbox Code Playgroud)
也有for case(几乎是相同的case,如switch报表),所以它看起来是这样的:
for case let b as B in objects {
// use b which is now of type B
}
Run Code Online (Sandbox Code Playgroud)
另一个好的表达是:
for case let b as protocol<B, C> in objects {
// use b which is now of type protocol<B, C>
}
Run Code Online (Sandbox Code Playgroud)
所以你可以同时使用两种协议的方法,属性等
| 归档时间: |
|
| 查看次数: |
175 次 |
| 最近记录: |