简体   繁体   English

协议一致性检查是否存在循环?

[英]Protocol conformance check in for loop?

I have two for loops that are trying to do the same thing: 我有两个试图做同样事情的for循环:

for item in components where item is UpdateableComponent
{
    item.update()
}


for item in components
{
    if let component = item as? UpdateableComponent
    {
        component.update()
    }
}

components is an array of Component objects. componentsComponent对象的数组。 UpdateableComponent is a protocol that basically makes a specific Component update on a regular interval. UpdateableComponent是一种协议,基本上可以按固定的间隔进行特定Component更新。 Component has subclasses, such as Timer, Player, Enemy, and other game-related classes, some of which conform to the UpdateableComponent protocol, and some that don't. Component具有子类,例如Timer,Player,Enemy和其他与游戏相关的类,其中一些符合UpdateableComponent协议,而某些则不符合。

The first loop throws the error that Component has no member update, which is true, but the UpdateableComponent protocol does. 第一个循环抛出Component没有成员更新的错误,这是正确的,但UpdateableComponent协议确实存在。 Why is the where clause not filtering the array? 为什么where子句不过滤数组? The second loop compiles, but would it give me the desired effect? 第二个循环可以编译,但是会给我想要的效果吗? It's not as clean as the first one though, and I feel they (should) achieve the same effect. 它不如第一个干净,我觉得他们(应该)达到相同的效果。

Why is the first loop not a valid option to filter the components array to objects that conform to the UpdateableComponent protocol? 为什么第一个循环不是有效的选项,无法将components数组过滤为符合UpdateableComponent协议的对象?

This is because there is no cast in the first loop from Item to UpdatableComponent. 这是因为在从Item到UpdatableComponent的第一个循环中没有强制转换。 The compiler only sees that you're trying to call update on the item which is of type component and doesn't take into account the fact that you're actually only calling it on an UpdateableComponent (we know that we only get UpdateableComponent from the loop filter, but the compiler doesn't). 编译器只会看到您正在尝试对组件类型的项目进行更新,而没有考虑到您实际上仅对UpdateableComponent进行调用的事实(我们知道,我们只能从循环过滤器,但编译器没有)。 The second loop has a direct cast, so the compiler knows for a fact that if component is not nil, if must be of type UpdatableComponent. 第二个循环具有直接强制转换,因此编译器会知道一个事实,即如果component不为nil,则if必须为UpdatableComponent类型。 The second loop will give you the same desired effect. 第二个循环将给您相同的期望效果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM