‘Fake error’ about immutable values when using popFirst() on Array

It’s been a while since I wrote any meaningful Swift.  How I didn’t miss the Swift compiler’s bullshit error messages.

var someArray = ["Foo", "Bar"]

if let foo = someArray.popFirst() {
    print("Who cares, we never get here anyway.")
}

That yields, on the popFirst() method:  “Cannot use mutating member on immutable value: ‘someArray’ is immutable”.

No it’s not.  It’s simply not.

For whatever reason, if you instead call popFirst() on ArraySlice – ostensibly indistinguishable from a real Array – it works just fine.

var someArray = ["Foo", "Bar"][0...]

if let foo = someArray.popFirst() {
    print("Yet this works correctly.")
}

Sigh.

I presume it’s trying to tell me something stupidly obscure about Swift’s byzantine type system.  Good luck finding out what.  Good luck even finding the definition of the popFirst() method, since Xcode claims it doesn’t exist if you Command-Control-click on it.  But Xcode can’t find most things, so that in itself says very little.

Undocumented Swift conditional compilation macros

swift/lib/Basic/LangOptions.cpp has most of the conditional compilation macros (called “Language Options” in the compiler internally).  Notably the swift() version macro is absent, and doesn’t seem to be defined anywhere…

At time of writing the two undocumented additions, to the os(), arch(), and swift() set, are _endian() and _runtime().

I have no idea if they’re useful or not – does anyone have to care about CPU endianness these days, really? – but there they are.

#if DEBUG in Swift

Sigh.

The Swift team give an impeccable impression of a group of people who’ve never actually tried to use Swift.

An incredibly basic compiler task is to provide code a way to distinguish between debug & release builds, in order that it can behave accordingly (e.g. change the default logging verbosity, change asserts from fatal to non-fatal, etc).

Long story short there is no way to do this that works correctly with swift build.

You can make it work with Xcode only by way of a simple workaround – you manually define a custom Swift flag in your target’s settings (here’s one of a bajillion explanations of how do this).  You end up with basically identical code to other C-family languages, e.g.:

#if DEBUG
    let logVerbosity = 1
#else
    let logVerbosity = 0
#endif

But there is no way, when using swift build, to specify custom Swift flags in your package config.

You can specify them manually with every single swift build invocation, e.g.:

swift build -c debug -Xswiftc ‘-DDEBUG’

But now you have extra work and the possibility of screwing it up (e.g. omitting the flag, or mismatching it to your actual build style).

The closest you can get is to use some undocumented, hidden Swift internal library functions:

func _isDebugAssertConfiguration() -> Bool
func _isFastAssertConfiguration() -> Bool

These are defined in swift/stdlib/public/core/AssertCommon.swift.

Only the first is likely to be useful.  The second applies in the case where you’re building not just for release but unchecked (-Ounchecked).  If you just want to conditionalise on release builds generally, you have to do !_isDebugAssertConfiguration().

The additional problem with this approach is that these are then, in your code, runtime checks.  And the compiler then thinks it’s being helpful by pointing out that some of your code that uses them is unreachable.

And of course Swift has absolutely no way to silence compiler warnings, or otherwise tell the compiler not to trust its reachability checks.

Sigh.

Update (February 2018)

While the above method – using the _isDebugAssertConfiguration() method – does still work at time of writing, in Swift 4.1, there are some marginally better ways now available.  There’s still not a proper solution, infuriatingly, but with some creativity, as you’ll see momentarily, you can get pretty close to expected functionality.

First alternative

This will only suit some cases, but its relative cleanliness & simplicity makes it appealing when it is an option.

You can use #if targetEnvironment(simulator).  This of course only distinguishes between the simulator and a real iDevice environment, though that can often be useful too, perhaps orthogonally to DEBUG vs RELEASE concepts.

Second alternative

Wrap all uses of _isDebugAssertConfiguration() inside a minimal set of functions.  All this gets you is a reduced (and fixed) number of unreachable code warnings, though.

For example:

func inDebugBuilds(_ code: () -> Void) {
    if _isDebugAssertConfiguration() {
        code()
    }
}

func inReleaseBuilds(_ code: () -> Void) {
    if !_isDebugAssertConfiguration() {
        code()
    }
}

You can then use these in a fairly streamlined way:

inDebugBuilds {
    print("Hello, I only greet in debug builds!")
}

inReleaseBuilds {
    print("While I only greet in release builds - aloha!")
}
Third alternative

It’s possible to do one better than the above, and eliminate those unreachable code warnings entirely.  Plus, doing so actually removes any use of unofficial APIs… but it requires abusing the official API a bit.

The built-in assert() method is implemented atop _isDebugAssertConfiguration() just the same as inDebugBuilds() is, above.  However, because it’s part of the Swift standard library, you don’t have to be concerned about its implementation, its use of private / undocumented language, compiler, or library features – that’s up to the Swift compiler team.  Most importantly, use of it in your code doesn’t emit an unreachable code warning.

So we can do something like:

func inDebugBuilds(_ code: () -> Void) {
    assert({ code(); return true }())
}

Ugly and obtuse, but functional and reasonably expected to work in all future versions of Swift.

You can similarly create a variant for release-build-only code, though it’s even hackier:

func inReleaseBuilds(_ code: () -> Void) {
    var skip: Bool = false
    assert({ skip = true; return true }())

    if !skip {
        code()
    }
}

Icky, but it works.  On the upside, you only have to define this ugliness in one place in your module, and then you can try to forget about its implementation. 😝

One caveat is that I don’t know if the above approach will properly strip out the unreachable code from your built binaries.

Another caveat with these is that since you’re invoking a function, you can’t do a natural if … else … pattern – instead you need explicit, distinct inDebugBuilds & inReleaseBuilds blocks.  So it can’t be completely like the vanilla #if DEBUG … #else … that C-family languages have had since before the dinosaurs.  You could create versions that take two closures as parameters – one for the affirmative case, one for the other… the trade-off is that your invocations are then a little more verbose and obviously function-cally, e.g.:

func forBuildStyle(debug debugCode: () -> Void,
                    release releaseCode: () -> Void) {
    var debugBuild: Bool = false
    assert({ debugBuild = true; return true }())

    if debugBuild {
        debugCode()
    } else {
        releaseCode()
    }
}

forBuildStyle(
    debug: {
        print("I'm built for debuggin'!")
    },
    release: {
        print("I'm built for the wild!")
    }
)

Up to your personal preferences as to which API you adopt, and which implementation you choose (streamlined but private-Swift-bits-dependent with bonus unnecessary compiler warnings, or official-APIs-only but hacky).