[swift-evolution] Constant initialization and unreachable code.

David Goodine dmgoodine at gmail.com
Wed Oct 19 06:50:45 CDT 2016

Hey all,

I don’t know if this is really an ‘evolution’ topic per se, and I’m not on Swift Dev, but thought someone here could shed some light on this.

Often when developing code, if I need create mode switches (constant Bools) so that I can move back and forth between different features/implementations for testing, developing experimental features, migration, etc.  Currently if I write the following:

let useFoo = true

if useFoo {
// Foo code
} else {
// Non-Foo code

I will get compiler warnings either way that there’s unreachable code based on the value of useFoo.  That makes sense in most cases, but in some cases I need to leave the code as is for a while, and I hate leaving long-standing compiler warnings in production code.  (If it’s yellow, you need to pay attention to it.)  So I poked around and discovered that if I use the following declaration of useFoo, the warnings go away.

let useFoo = { return true }()

So, the question is, is this intentional? The compiler could certainly ascertain that useFoo will always be true and carry out the same dead code detection as for the first declaration.  If this isn’t intentional, and the compiler may at some point optimize away the closure and trigger dead code warnings, I might come up with a proposal that there is some idiom that allows one to do the above without the warnings.  I’m really not a fan of #define (because it’s just butt-ugly in such a beautiful language), but its existence is unavoidable for some cases.  

And, as I write this, I realized I haven’t tried declaring useFoo as var, but I expect that would trigger a warning that useFoo is not modified and should be defined by let.  I think this is a use case that, for practical purposes, should be covered to allow this type of evolution of code without generating warnings.  If the current behavior is intentional and going to stay, then that’s probably the best solution.


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20161019/a9c43c99/attachment.html>

More information about the swift-evolution mailing list