Archive for January, 2016

Book Review: The Useful Book

Screen Shot 2016-01-13 at 3.40.53 PM

Netgalley recently allowed me access to Sharon and David Bowers’ The Useful Book (Workman Publishing, $20) to see what I made of it.

For someone who holds DIY and “making” close to her heart, it’s a fun but imperfect find, featuring over a hundred practical how-to “skills” that you might not have picked up from traditional sources like Home Economics class or Wood Shop.

The book consists of two sections, one focusing on home skills, the latter on handyman ones. The page layout is easy to follow with sensible columns, lots of art, and simple step-by-step instructions. You can dive into a random page and grab some how-to without having to read from cover-to-cover.

I see this more as a gift book suitable for a coffee table than a much-loved reference. I found the coverage to be entertaining even when I disagreed with some of the suggested approaches or found them missing important details.

I warn you that some of the topics may seem a little underwhelming (“How to boil water” and “How to care for your (sewing) needles” spring to mind). The practical applications (“Superstitious folk wisdom advises that, to protect a child from evil spirits during sleep, a key must be slipped under his or her pillow”) may not exactly fit my corner of the DIY community.

For example, my physicist husband points out that there’s absolutely no reason to stick with cold water for boiled water (#1, “How to Boil Water”), as dissolved mineral danger is hyped up in his opinion. He adds that the reason you want to cover your pot is to prevent heat from escaping, and make your water boil faster, more than losing water content through steam.

I learned that I could have drained my tofu (#47, “How to Cook with Tofu”)  — a step I have never taken and am unlikely to adopt even now, but was happy to learn about. (I use my hand to provide top-down pressure as I slice tofu sideways first before doing rows and columns.)

We like bright lights in our workspaces and are unlikely to swap them out for cost-saving lower wattage units (#177 “How to Slash Your Electricity Bill”)

This isn’t to say there isn’t good advice on-hand, like sanding rough spots when patching a wall but I do wish that they’d offered advice like checking the inside of a bike tire as well as looking at the outside for possible reasons why it went flat, a critical tip in goathead country.

If you’re looking for a nice housewarming gift for a new couple, this title could suit the bill. If you’re looking for a deeply geeky read, this probably isn’t going to be your cup of tea.

A few thoughts on Swift symbology

In Swift, ? is an identifier character and ⚽︎ is a legal operator. You can assign M_PI to π or construct an ° operator that says “treat this double as being sourced from degrees”

public let π = M_PI
postfix operator ° {}
postfix func °(degrees: Double) -> Double {
    return degrees * π / 180.0

Unicode support expands code to include a more flexible symbol set for development. The most obvious use case is regional. Swift’s Unicode internationalizes the language, enabling developers to establish  meaningful symbols appropriate to their native tongues.

“let 你好 = "你好世界”


Swift developers have a love-hate relationship with these symbols, as they can provide beneficial clarity at the cost of easy typing.

The character sets are extensive. While the operator characters are easily enumerated, the symbol ones are much larger. This gist iterates through the ranges listed in the Swift Programming Language. Each set consists of header characters (legal starting characters) and additional characters that can be added but not used to start an operator or symbol.

Some symbols map beautifully to existing mathematical constants (π and τ for example) and to operators such as those used in set mathematics. The SwiftExperimental stdlib source implements a suite of these:

infix operator ∪ { associativity left precedence 140 }
infix operator ∪= { associativity right precedence 90 assignment }
infix operator ∩ { associativity left precedence 150 }
infix operator ∩= { associativity right precedence 90 assignment }
infix operator ⨁ { associativity left precedence 140 }
infix operator ⨁= { associativity right precedence 90 assignment }
infix operator ∈ { associativity left precedence 130 }
infix operator ∉ { associativity left precedence 130 }
infix operator ⊂ { associativity left precedence 130 }
infix operator ⊄ { associativity left precedence 130 }
infix operator ⊆ { associativity left precedence 130 }
infix operator ⊈ { associativity left precedence 130 }
infix operator ⊃ { associativity left precedence 130 }
infix operator ⊅ { associativity left precedence 130 }
infix operator ⊇ { associativity left precedence 130 }
infix operator ⊉ { associativity left precedence 130 }

Other symbols and operators offer less compelling use-cases like this custom quarter of Pi (or eighth of pie) that I threw into a utility math file:

public let ? = π / 4.0

or this custom pick operator that selects n items from a set:

infix operator ⛏ {}
public func ⛏(set: Set<T>, count: Int) -> Set<T> {
    func rnd(i: Int) -> Int {return Int(arc4random_uniform(UInt32(i)))}
    var items = set, chosenItems: Set<T> = []
    (1...count).forEach { _ in
        let whichOne = items
    return chosenItems

Set(["a", "b", "c", "d", "e"]) ⛏ 3 // pick 3 members

When pushing APIs beyond common keyboard characters, carefully consider usage. Symbols, no matter how pretty, can be ridiculously hard to type. Some such as • are easily typed on US keyboards (Alt-8) but may be more difficult to access on other global layouts.

While coding, you don’t want to continually have to cut and paste from your declarations or require the system Characters picker to complete writing each line of code:

Screen Shot 2016-01-13 at 12.08.45 PM

For in-house symbols, the System Preferences > Keyboard > Text pane offers simple text-replacement. In the following settings, when I type (chicken) in Xcode, OS X automatically replaces it with ?. For common, internal API symbols, that’s a trade-off many developers are willing to make.

Screen Shot 2016-01-13 at 12.09.06 PM

A more important question arises in what you expose for API consumption outside your immediate group, especially when you push beyond native language support.

In such cases, simplicity and ease-of-lookup should weigh heavily in your decision making. Adhere to the principle of least astonishment. Limit your use of exotic characters (that is, exotic outside your specific development environment) to maximize your expected rewards compared to the costs of typing and discoverability.

For globally published APIs, universal standards offer the best opportunities to integrate Swift symbology into your code. Even so, you may still prefer sum and product to ∑ and ∏ for simple, consumer convenience.

As a final amusing note, Chris Lattner has assured the integrity of at least a portion of the symbol set. On Swift Evolution, he wrote that any proposal for future Swift updates that breaks

let ?? = "moof"

will not be tolerated.

What’s up in Swift Evolution


SE-0018 Flexible Memberwise Initialization proposal returns to Evolution list for further development without acceptance or rejection. It proposed to extend memberwise initialization from structs to classes, to avoid excessive boilerplate code. Reception on the list was mixed about specific implementation details but many devs like the core idea. Apple promises specific feedback soon.

Active Review

SE-0010 proposes to add a non-mutable StaticString.UnicodeScalarView. (I like it). SE-0013 will remove partial application for non-final “super” methods. I’m agnostic on this one and haven’t spent much time looking at it. SE-0020 aims to extend  build configurations to differentiate code based on the current Swift language release. (I like this one too!)


There’s Doug Gregor’s SE-0021, which provides more specific ways to reference possibly overloaded functions within modules and his SE-0022, which creates sensible argument-label-aware selectors vs the current string approach. (+1 for both.)


SE-0011 was accepted for Swift 2.2, differentiating typealias implementation from associatedtype requirements in protocols.


Every time I think I’m making headway in reading the list, my unread messages count goes back up above 500, and it’s overwhelming. I’m keeping an eye on a few topics that probably aren’t generally of interest to most developers.

There’s also topics right now about evolving sequences and collections, adding more stdlib features from other languages, tweaking protocols, etc.

There were two proposal discussions that I thought were really cool: adding an “entirely uninitialized” alternative to nil called none and adding named invariants for variable declarations. These were greeted…poorly. I encourage you to look them up, both from Amir Michail.

There was conversation on closures with an inferred return values but that seems to have died pretty miserably too. In the current version of Swift, inferred return is limited to one-line closures. It seems you could rule out branching scenarios — it would have to be an unambiguous endpoint — but this was argued over and faded away.

I vaguely remember seeing something about eliminating trailing closures for any multi-closure parameter calls but I can’t seem to track it down now that I’m writing this stuff up. In any case, I approve because doing one branch of success-error as an argument and the other as a trailing closure makes no sense.

What on-list topics caught your eye? Drop a comment or tweet.

Make this Swift-er: Coordinate distances

Here’s Jamone Kelly‘s starting point. If you want to hop into the revisions, there’s a slightly earlier starting point but this is his properly working version.

After playing “Make it Swifter”, here’s my version.

I struggled a bit with the operator before settling on using the ° symbol. In my mind, I’m thinking the operator says “treat this value as degrees” and transparently perform any conversion to radians. I didn’t want to  put a radian or angle symbol after it, which really doesn’t read as well to mean “radian-ify this”.

I’m not married to this approach. In hindsight, I might have created a new type Angle with separate initializers (init(degrees: Double), init(radians:Double)) and degreeRepresentation and floatRepresentation members. It just seems like a lot of excess work for relatively little reward here. (Although as a re-usable library component, it would probably be nice.)

Settling on the enumeration was hard too because I was leaning towards Units with cases of Imperial and Metric, but then associating these specific raw values didn’t make sense. I ended up with wordier versions that supported the raw values being stored.

I am still using uppercase enumeration cases despite pressure to convert them to lower case members.

Paired assignments emphasize the parallel math, which feels both Swift-y and transgressive. I like them when they reflect corresponding operations, although your mileage may vary.

If I were pushing on this, I’d of course comment a lot more and probably add in some kind of protocol to support interop (representation and initialization) with CoreLocation.

How would you re-design this code? Drop a gist and share.

Xcode 7.3 beta introduces enhanced code completion

Screen Shot 2016-01-11 at 3.12.20 PM

Xcode 7.3 beta release notes:

Code completion provides better matches with fewer keystrokes and makes it easier to find what you’re looking for.

You can type just the uppercase letters of a method name. Typing “myDelegate.tveh”, where myDelegate is a UITableViewDelegate, gives tableView(_ tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat as the first completion.

You’ll also get completions that better match your intent, so typing “myView.color”, where myView is a UIView, gives every property containing the “color” substring, like “tintColor” and “backgroundColor”. (22429862)

Not sure how “e” for “estimate” is uppercase, but I get the point. Neat stuff. (update: changed “fuzzy” to “enhanced” in the headline because it really wasn’t very fuzzy, wuz he? Also, added some line breaks to make it more readable.)

Thanks, Robert Payne

Toolchain Switching

New to Xcode 7.3 beta, you can select Preferences > Components > Toolchains without having to launch Xcode from the command line.

Screen Shot 2016-01-11 at 2.45.13 PM

Screen Shot 2016-01-11 at 2.45.28 PM

Things that you probably figured out on your own:

  • You can’t use beta toolchains for App Store compilations
  • The Playground is limited to the default toolchain. (And they’re still a bit laggy for massive playgrounds.)

Things you might not have thought of but are worth knowing:

  • The code migrator doesn’t work with beta toolchains. It’s strictly limited to the default toolchain.

The Swift Evolution proposal SE-0009 rejection

Here is Doug Gregor’s post on why. I’m posting his full text here as a courtesy to my Twitter followers who are not Swift-Evolution subscribers. A link to the rejection appears in the original proposal after the Rejection status as “(Rationale)”.

The review of SE-0009 “Require self for accessing instance members” ran from December 16–20, 2015. The proposal has been rejected.

This proposal spawned a massive, polarized discussion with 200+ messages involving 80+ participants. We’re thrilled at the enthusiasm and thank all who participated. There were many, many interesting points made, along with experience reports from various Swift code bases, ideas to help mitigate the concerns that motivated the proposal, and so on. Quantitatively, the overall community assessment of the proposal was roughly 5:2 against requiring “self.”.

The core team agreed that this proposal is not the right direction for Swift. There are a number of reasons for this decision:

  • Mandatory “self.” introduces a significant amount of verbosity that does not justify itself with added clarity. While it is true that mandatory “self.” may prevent a class of bugs, the cost of eliminating those bugs is fairly high in terms of visual clutter, which goes against the generally uncluttered feel of Swift. Paul Cantrell put it well in his review when he said, “anything that is widely repeated becomes invisible.” Swift aims to avoid such boilerplate and repetition in its design, a principle also espoused by the Swift API Design Guidelines.
  • The requirement to use “self.” within potentially-escaping closures is a useful indicator of the potential for retain cycles that we don’t want to lose. Additionally, developers can optionally use “self.” when they feel it improves clarity (e.g., when similar operations are being performed on several different instances, of which “self” is one).
  • The name-shadowing concerns behind the mandatory “self.” apply equally well to anything found by unqualified name lookup, including names found in the global scope. To call out members of types as requiring qualification while global names do not (even when global names tend to be far more numerous) feels inconsistent, but requiring qualification for everything (e.g., “Swift.print”, “”) exacerbates the problem of visual clutter.
  • Individuals or teams that feel that explicit “self.” is beneficial for their own code bases can enforce such a coding convention via tooling with the status quo. If this proposal were accepted, those opposed to the proposal would effectively have no recourse because the language itself would be enforcing “self.”.

Doug Gregor
Review Manager

Swift development realities

Swift 3 is going to break your code. It’s a given. It was a given when the Swift team presented, opened the Swift evolution repo and mailing list, and allowed an early peek into already accepted proposals. If you’re not living in beta land, you will see it when 2.2 starts to warn what 3.x will break.

It’s a given when you see how Swift is reworking the way it interfaces with Foundation and adopting new guidelines for translating Objective-C APIs. It’s a given when there are still active and lively discussions about how the error system will evolve, how the standard library is going to change, and what default inheritance rules should be.

With this reality, you can choose one of the following approaches:

  1. Avoid Swift. C and Objective-C and their C++, web, and cross-platform friends can still help you build and sell product.
  2. Cautiously test the Swift waters but delay full adoption.
  3. Embrace Swift and fight to maintain the language’s immediate integrity for production code.
  4. Embrace Swift and try to get as much pottery broken and re-geared in the 3 update to ensure that the 4 update and later involve relatively minor changes, adding features instead of breaking them.

I vote for option 4.

All changes are costly but large early changes are ultimately less expensive than slow yearly language updates. That’s not to say that changes aren’t traumatic or expensive, regardless of when they happen. They are.

Imagining that all the important changes can be adopted at once is a fantasy. But the sooner the language approaches stability, the more both the developer community and your customers will benefit. You can complain from the sidelines or get involved in setting the direction.

You can’t properly develop in Swift without preparing for refactors. The two core realities of adopting Swift right now are writing tests and documenting the hell out of everything[1]. Allocating time and building tests and comments are part and parcel of getting ready for the next big flood.

The flood is gonna happen. Will you be there?

[1] If the tests work, great. If not, your comments address the “what was I thinking when I wrote this” bit that moves beyond “self documenting code” and “obvious method names”

And then there was .None: when to nil and when to not

I was updating some very old code today, when I stumbled across a return .None for some function that returned T?. It’s been pretty much forever since I have used anything other than return nil and I thought I’d take a quick moment to figure out where .None belongs in my life.

It didn’t take long (thanks, Olivier) to shake out a sketchy rule of thumb. It’s this: if you’re using pattern matching, you can go use .None if you really want to. If you are returning an optional value, just use nil.

if case (.None, .None) = items { return nil }

Even if you can theoretically use:

if case (nil, nil) = items { return nil }

skipping the .None in pattern matching just doesn’t feel as nice, especially when you’re doing any conditional binding:

if case (.Some(let x), .None) = items { ... }


if case (.Some(let x), nil) = items { ... }

but then again, Swift now supports x? vs .Some(let x), so I’m also actually pretty okay with:

if case (let x?, nil) = items { ... }

Conclusive? Not especially but there you have it.

If you are building a custom enumeration and your conversation regularly includes terms like monads and functors, you’re on your own.