gpt4 book ai didi

swift - 类型转换和 for 循环中的位置

转载 作者:IT王子 更新时间:2023-10-29 05:42:40 31 4
gpt4 key购买 nike

我有以下场景:

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

最佳答案

还有 for case(与 switch 语句中的 case 几乎相同)所以它看起来像这样:

for case let b as B in objects {
// use b which is now of type B
}

另一个很好的表达方式是:

for case let b as protocol<B, C> in objects {
// use b which is now of type protocol<B, C>
}

因此您可以同时使用来自两个协议(protocol)的方法、属性等

关于swift - 类型转换和 for 循环中的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31021723/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com