Archive for December, 2015

Swift Evolution: Calendar update (and tuple comparison)

Today is the last day to vote on SE-0014, constraining AnySequence.init.

SE-0015 voting begins today for a very short 2-day consensus on tuple comparison. This is a Lily proposal that implements comparison for n-arity tuples using automagic gyb coding:

It’s annoying to try and compare tuples of comparable values and discover that tuples don’t support any of the common comparison operators. There’s an extremely obvious definition of == and != for tuples of equatable values, and a reasonably obvious definition of the ordered comparison operators as well (lexicographical compare).

Beyond just comparing tuples, being able to compare tuples also makes it easier to implement comparison operators for tuple-like structs, as the relevant operator can just compare tuples containing the struct properties.

This looks ridiculously +1 straightforward.

How to curl raw content from gists

In my most recent post about installing Ubuntu/Swift, I glancingly referred in a screenshot to pulling swift source from a github gist. I thought it was useful enough a tip to pull out to its own post.

Say you have a gist, for example: this one, which is located at I threw this sample together to help some Linux-ers work with incomplete Foundation and Standard Library implementations on Ubuntu.

If you grab this link’s content from the terminal command-line using curl, you’ll end up with the page’s HTML source, which is pretty much not what you want to compile:

Screen Shot 2015-12-20 at 11.20.36 AM

Instead, replace with and append /raw to the url:

This adjusted URL bypasses the HTML page contents and accesses the raw text stored within the gist. Just redirect with > into a Swift file and you’re ready to compile.

Screen Shot 2015-12-20 at 11.24.02 AM

I hope this tip helps minimize the misery of sharing code with Ubuntians.

Living la vida Linux

This morning, I finally broke down and installed Ubuntu 15.10 into Virtual Box. I didn’t take notes, which I am now kicking myself for because it didn’t occur to me until after I had gone through the entire annoyingly tweaky process.

Here are the highlights.

First, I installed Virtual Box. I mostly went with the directions in this Simple Help write-up. The directions are 15.04, but they worked fine for 15.10. Per the write-up, I went with all the defaults. It took an hour or more for the Ubuntu install to get itself set-up. Prepare to head out for a few errands.

Next, I spent time familiarizing myself with Ubuntu, finding the terminal, chsh’ing to tcsh from bash (I had to apt-get tcsh) and setting up my .cshrc. I also installed lns (bless it) and downloaded the latest 15.10 Swift 2.2 snapshot from

Then I symbolic linked swift and swiftc into my ~/bin folder, checked that I could run them both from wherever, and then set to working on getting ssh running so I didn’t have to use Virtual Box directly.

To do that, first I had to apt-get install OpenSSH-server, which was no big deal, and then what took the most time was figuring out how to set up networking. Turns out that you need to shut down the machine, set up Adapter 1 to use Bridged Adapter (thanks aciidb) and the find the 10.0.whatever-ip-address using if-config after rebooting. (Mine was

Once I got past that, I was able to ssh in over from my Mac and start using Swift. I began with a simple shell script (thought that was easier) and then moved onto swift and then swiftc compilation.

As Mike Ash pointed out, when encouraging me to use ssh with Virtual Box, you gain all the utility of your normal terminal session including copy, paste, etc without having to deal with mouse capture, etc.

Survey: How would you rename associated type?

The typealias keyword is overloaded to declare two kinds of types:

  1. Type Aliases (alternative name for an existing type)
  2. Associated Types (placeholder name to type used as part of a protocol)

Proposal SE-011 declares, “These two kinds of declarations are different and should use distinct keywords. This would emphasize the difference between them and reduce some of the confusion surrounding the use of associated types.”

What keyword do you think is a better replacement for typealias? Help out in this poll.

Community responses, from the proposal:

  • “I think this is a great idea; re-using typealias for associated types was a mistake.” -John McCall
  • “Agreed.” -Chris Lattner
  • “+1 to the proposal, emphasizing the distinction is important; and I like “associated” as the keyword for this purpose, too.” -Dmitri Gribenko
  • “+1 for using a distinct keyword for associated types” -Ilya Belenkiy

Bidding farewell to currying

I love this code. It enables me to pass any function and then a set of coordinates. So if I want game pieces to move, for example, using a sin pattern, I can establish a partially applied version of the function that’s specific to sin — or any other pattern I want to use: wiggles, sawtooths, etc.

Once established, I can then once again apply for each game move from the piece’s starting position to ending position. The returned function is now ready to be traversed to create a SpriteKit-ready Bezier path for moving.

With Swift 3.0, currying is saying goodbye and with it, the simple elegance of partial application.

I’m off to refactor this code. Wish me well. Suggestions welcome.

Update: Here’s what I’ve got. Thanks to Mike Ash for simplifying the “return { stuff in” patterns. Of course, the worst thing about all this after worrying about this for days, the result isn’t horrible and it’s highly likely that I’ve made a fuss about nothing big.

Dear Erica: Help me refactor

Mike writes: How can I refactor this so I don’t use the same fail logic twice and won’t incur the costs of the expensive call unless needed? Is there an elegant one-line condition I can use to replace the nesting and redundancy? Using guard for early exit on myCondition is a no-go.

Here’s the code:

// Not ideal: Dupe fail logic
if !myCondition {
    if let myValue = getExpensiveComputationResult(){ 
        // Do my stuff 
    } else { 
        // Fail logic 
} else {
    // Fail logic AGAIN

// Also not ideal: computation always processed regardless of myCondition
if let myValue = getExpensiveComputationResult() where !myCondition { 
    // Do my stuff 
} else { 
    // Fail logic 

A lot of developers new to Swift miss compound if statements. These consist of comma-delineated expressions which are evaluated in order. Compound if statements can include constant binding as in the following refactored code.

func expensiveCall() -> String? {
    print("EXPENSIVE!"); return "Expensive"

if !myAutoFailCondition, 
   let foo = expensiveCall() {
    print("Success, but expensive")
} else {
    print("Fail condition")

This example short-cuts if the “myAutoFailCondition” is true and the expensive function is never called. I encourage you to try this out in a playground.

The Swift if statement’s components can include a single expression that evaluates to true or false, an optional-binding condition, an availability condition, or a case condition. Always put the simple expression first or you’ll need to use where to separate it from the other kinds of checks. You’ll find the full grammar at the back of the Swift Programming Language book.

Naturally final classes in Swift

When was the last time you subclassed a class you created natively in Swift that wasn’t part of the Cocoa system? How often do you find yourself subclassing non-Cocoa types now that protocol extensions and regular ordinary extension extensions exist?

If your answer is somewhere between 0% and 5%, you’re fairly typical. Reference types are no longer tightly coupled with inheritance under Swift’s type system.

Pushing further, how often do you create classes and subclasses with the intention that they be furthered subclassed by API clients outside a particular module? (Assuming, of course, you’re not Apple, and you’re not writing views and controllers…)

Update: Matthew Johnson asked that I run this survey. Thank you for your participation.

When subclassing becomes the exception rather than the rule, is it time to consider making classes final by default? Or would it be better to seal modules as internal-by-default so public classes cannot be subclassed outside their module of origin.

Debate is currently raging on the Swift evolution list about how this might be approached, whether it should be done at all, and if classes could be designed to force calls to superclasses for overridden methods (“requires super call”).

John McCall writes:

Our current intent is that public subclassing and overriding will be locked down by default, but internal subclassing and overriding will not be.  I believe that this strikes the right balance, and moreover that it is consistent with the general language approach to code evolution, which is to promote “consequence-free” rapid development by:

(1) avoiding artificial bookkeeping obstacles while you’re hacking up the initial implementation of a module, but

(2) not letting that initial implementation make implicit source and binary compatibility promises to code outside of the module and

(3) providing good language tools for incrementally building those initial prototype interfaces into stronger internal abstractions.

All the hard limitations in the defaults are tied to the module boundary because we assume that it’s straightforward to fix any problems within the module if/when you decided you made a mistake earlier.

So, okay, a class is subclassable by default, and it wasn’t really designed for that, and now there are subclasses in the module which are causing problems.  As long as nobody’s changed the default (which they could have done carelessly in either case, but are much less likely to do if it’s only necessary to make an external subclass), all of those subclasses will still be within the module, and you still have free rein to correct that initial design mistake.

A thought from Joe Groff:

Robust subclassability requires conscious design just like all other aspects of API design.

Updated to add from Jordan Rose:

The interesting thing about this is that the “error of omission”—of failing to think about whether a class should be final—is worse than the alternative. Ignoring optimizations for a minute, a class that starts out ‘final’ can certainly become non-final later; it doesn’t change how the class is currently used.* For a lot of library evolution questions, this is the preferred answer: the default should be safe, and the designer of the class can choose to be more aggressive later.

Evolve or die: The Swift storm rages on

Generic enhancements for Swift 3.0

I loved this post, which summarizes where things are and where things may yet go with respect to generics. I’ve posted before about several of these wish-lish items and this response by Doug Gregor to a post by Matthew Johnson covers not only what may be coming down the line (or not) but also why (or why not).

Bring me a Higher Love Kinded Type

There’s a long discussion about Higher Kinded Types such as monads, functors, and so forth ranging on-list. This isn’t something I’m particularly into and it reads to me as, “This stuff is cool” “Give some practical examples of how Swift coding would benefit.”  “But this stuff is cool.” I think I’m entirely missing the point.

Property Behaviors

Here’s a particularly cool proposal from Joe Groff that abstracts out common implementation patterns for annotating properties. This approach would allow the team to develop a library of common behaviors (vs hard-coding them into the compiler).

The behaviors could be expanded, tweaked, and used upon demand by annotating properties with parenthesized keywords. Not just lazy but lazy on steroids. I’m feeling very +1 on this and I learned the metasyntactic phrase “runcible“. Win.

Refactoring Code

I’ve now spent several hours modernizing code. Of all the issues, the var ones ended up being the trickiest to deal with, for example:
public func imageFromVImageBuffer(var buffer: vImage_Buffer) -> UIImage? {
when using Accelerate, which translated to
public func imageFromVImageBuffer(buffer: vImage_Buffer) -> UIImage? {
    var buffer = buffer
Not a huge deal, but…you know, ugly. I had to fix guard vars, if vars, for vars, case vars, etc.
A few interesting situations with ++ and — popped up, and were generally solved either with extra variables or defer statements. The original in this case was return (index, self[index++]):
defer {index = index.successor()}
return (index, self[index])
Of the 3.0 changes,  the var parameter ones took the most time, followed by ++/–.
The for-loop ones were trivial and I had exactly one (1) keyword `escape` issue that I’ll delay fixing until the language changes. To be fair, I did have to kill and refactor a few dozen currying calls, but that’s to be expected since the code was for a chapter that introduced the concept of currying. I don’t consider those to be common applications. Call it 3, maybe 4, *real* (useful, realworld) curries among many calls. There’s still plenty of code to review though. All said, though, the process was less horrible than it might have been.

Updated linter

Just updated my testlint project ( to start searching for Swift 3.0 issues. For example, SE-0003 will remove var parameters. So this will no longer compile:

 if var testStream = OutputStream(path: aPath) {
     print("Testing custom output", toStream: &testStream)
     print("Hello ", terminator: "", toStream: &testStream)
     print("World", toStream: &testStream)
     print("Output sent to \(testStream.path)")
 } else {
     print("Failed to create custom output")

Instead, you’ll need to use if-let and create a var inside the success branch.

if let outputStream = OutputStream(path: aPath) {
    var outputStream = outputStream
    print("Testing custom output", toStream: &outputStream)
    print("Hello ", terminator: "", toStream: &outputStream)
    print("World", toStream: &outputStream)
    print("Output sent to \(outputStream.path)")
} else {
    print("Failed to create custom output")

My linter started off as a complete hack, in response to SwiftLint‘s minimal beginnings. I kept working on the repo because (1) I had complete control over it and (2) it offered many more rules that I found valuable. It’s still a complete hack but it’s evolved into a way I can explore style rules in preparation for writing Swift Style.

It is still not a great linter (it goes line by line instead of parsing because I didn’t want to use inter-process hacking and it relies on regex, waving my hands, chicken entrails, etc). However, it’s been an amazing way to start thinking about the way I do and should write Swift.

I think you’d probably get more out of my comments in Linter.m than via daily use. Just thought I’d let you know that it was updated.