简体   繁体   中英

Why is the indirect keyword needed in recursive Swift enumerations?

I understand what indirect does. What I don't understand is why this keyword is needed. Doesn't the compiler have enough information to figure this out on its own?

enum Foo {
    case Bar(Foo)
}

The code above won't compile unless it's marked indirect , but the compiler can already detect that it's indirect because it uses the same type again. Even if we do something more complex, it should be able to figure this out.

enum Foo {
    case Bar(Baz)
}

enum Baz {
    case Bob(Foo)
}

Even here the compiler has enough information to know that Foo and Baz are recursive. Haskell, for instance, needs no such keyword for similar recursive types, so obviously it is possible to build such a thing into a compiler.

So again, why do we need the indirect keyword?

Swift doesn't want to figure this out. It wants to be told explicitly, so it's sure that the code that you wrote is the code that you wanted to write.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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