Non-review: The Einstein Prophecy


So this month’s Kindle First picks showed up in my inbox from Amazon Prime and among them was this: The Einstein Prophecy.

The blurb (in part):

As war rages in 1944, young army lieutenant Lucas Athan recovers a sarcophagus excavated from an Egyptian tomb. Shipped to Princeton University for study, the box contains mysteries that only Lucas, aided by brilliant archaeologist Simone Rashid, can unlock.

These mysteries may, in fact, defy—or fulfill—the dire prophecies of Albert Einstein himself.

Did I somehow miss the moment when Einstein became a religious figure? I mean, “You believe in a God who plays dice, and I in complete law and order in a world which objectively exists.” “IT IS A PROPHECY”

Things you can gather from this post:

  1. I am knee-deep in writing about printing, debug printing, output streams, mirroring, quick looks, and so forth and will take any excuse to grab a break because my brain is about to melt from minutia.
  2. I am so picking this one as my Kindle First choice for this month. (You get to pick from four of them.)
  3. I hope Abraham Lincoln, Vampire Hunter will show up for a quick cameo.
  4. The foundation of morality should not be made dependent on myth nor tied to any authority lest doubt about the myth or about the legitimacy of the authority imperil the foundation of sound judgment and action, ” doesn’t sound like a man who will utter vague prophesies for a summer potboiler.

Oh what the hell. Here’s some more

Struggling to decipher the sarcophagus’s strange contents, Lucas and Simone unwittingly release forces for both good and unmitigated evil. The fate of the world hangs not only on Professor Einstein’s secret research but also on Lucas’s ability to defeat an unholy adversary more powerful than anything he ever imagined.

Swift: Hunting down the fleeting debugPrint differentiation

Yes, I had to build a little test bed to find items that printed differently in debugPrint than they did in print. I thought I’d share. Surely this kind of bizarre little implementation of a command-line test will be of interest to someone out there.

You might ask: why not playgrounds. The answer is that printing to any output stream type (including strings) crashes playgrounds. A playground version would use XCPlayground to continue execution instead of a run loop.

import Cocoa

// Items to check
//let x = "Snoop"
//let x = 1...5
let x = UnicodeScalar(0x1f601)

// Build test cases
var a = ""; print(x, &a, appendNewline:false); print(a)
var b = ""; debugPrint(x, &b, appendNewline:false); print(b)

// Compare and alert
func ExitAfter(t: Double, _ status: Int32) {
        numericCast(UInt64(t * Double(NSEC_PER_SEC)))), 

if a != b {
    // Success
    NSSound(named: "Sosumi")?.play()
    ExitAfter(0.5, 0)
    CFRunLoopRun() // stick around to produce sound
} else {print("No")}

Swift: Revisiting printing with string formats

Support for NSLog is baked into Swift via the Foundation framework. The NSLog utility function offers string-formatting services that log error messages to standard error and to the system console. Unlike print, NSLog supports standard %-delimited format specifiers as well as Apple-supplied extensions. Apple’s String Programming Guide details its support for and extensions to the IEEE printf specification.

You pass NSLog a format string followed by a variadic list of Objective-C-compatible parameters. The parameters map to specifiers embedded within the format string.

NSLog("Dictionary: %@, Double: %0.2f", ["Hello":3], 2.7)

Swift supports format specifiers as one way the standard library offers to create and initialize strings.

/// Returns a `String` object initialized by using a given 
/// format string as a template into which the remaining argument 
/// values are substituted according to the user’s default locale. 
init(format: String, arguments: [CVarArgType])

Using this initializer, you can easily build a custom logger that mimics NSLog:

public func SWLog(format: String, _ args: CVarArgType...) {
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = 
            "mm:ss:SSS", options: 0, 
            locale: NSLocale.currentLocale())
    let timeString = 
    print("\(timeString): " + 
        String(format: format, arguments: args))

This implementation minimizes printed time to just minutes, seconds, and fractions of a second compared to the exhaustive date output provided by NSLog. For example:

SWLog("Hello world") 
SWLog("Formatted double: %2.3f", 5.2)  
SWLog("Double plus string %2.3f, %@", 5.2, "Hello world")


55:40.706: Hello world 
55:40.707: Formatted double: 5.200
55:40.708: Double plus string 5.200, Hello world

You cannot use format arguments to express Swift constructs like enumerations, functions, and structs. They do not conform to the CVarArgType protocol. For example, this line results in a compile time error:

SWLog("Struct: %@, Int: %03zd", CGPoint(x: 50, y: 20), 5)

Instead, add Swift string interpolation to format string initialization. This approach combines the flexibility and nuance of format strings with pure Swift types:

SWLog("Struct: \(CGPoint(x: 50, y: 20)), Int: %03zd", 5)

Swift: To the max

If you have code around that uses lots of F’s (e.g. 0xFFFFFFFF) or capital letters (e.g. UINT32_MAX), consider replacing these constants with built-in Swift versions.

Swift offers .max and .min properties for many numeric types. For example:

public func Random01() -> Double {
    return Double(arc4random()) / Double(UInt32.max)

How to convert the new Swift beta books

Several people have asked (waves hi to Aaron) how to grab the latest Swift book as a PDF. My copy of the Prerelease book is encrypted. I assume yours is too. You probably want to do something like this not this, but I haven’t fully tested yet because I’m knee deep in a chapter about printing and mirroring.

If you can’t fetch with site sucker, just wget from the command line:

wget -r -l1 --no-parent

I’ll leave the whole “set up calibre page layout” thing as an exercise for the reader but if you have some good ways to produce good PDF output please drop a note.

Swift Playgrounds: Arranging Assistants For Speed

Screen Shot 2015-07-01 at 10.39.28 AM

Sometimes, the best way to optimize a playground is by moving nearly every line of code out of it.

Consider the layout used in the screenshot at the top of this post. The playground is at the very top. It includes just one line that runs a Go function.

The remaining assistant area is split in two. To the left is a Sources editor and to the right is the playground timeline output. It’s displaying the results of a capture value sequence for the GameplayKit random samples I posted about yesterday. I wasn’t fully happy with the layout I’d been using and between then and now, came up with this one.

Simulating a hundred thousand random samples is processor heavy. This layout enables me to use built-in playground visualization features and module compilation optimization. The results are terrific: fast interactive exploration with the side-by-side presentation you normally get in the default playground layout.

Like the hacks? Read the book.

Help me pick a constant

Here’s the equation:

Official Swift version N = Unofficial Swift(version:N-k)

Help me figure out the constant to use.

Solve for “k” free polls

Iterating Optionals

Pick out just the .Some cases using the ? operator:

let opts : [Int?] = [1, nil, 2, nil, nil, 5, 
    nil, 3, 8, 11, 2, 6, nil, 9]

// "1 2 5 3 8 11 2 6 9 "
for case let x? in opts {
    print("\(x) ", appendNewline: false)