Don’t attempt tech conversations after anesthesia

Does anyone know if I need to capture self as weak in a UIView.animation block?

Once I was afraid. I was petrified. Scared I couldn’t render without view at my side. Then I spent so many nights thinking how you did me wrong, and I referenced strong, and I learned how to pass my ARC along…

And now you’re back from @nonescape. I just walked in to find you here with that sad look upon your face.

I should have made you dereference, should have made you leave your key, if I’d known for just one second, you’d need to be released

Go on now, walk out the door. I’m not the same calling instance, you’re not needed anymore

Weren’t you the one who tried to create a reference cycle with goodbye, do you think I’d crumble, deallocate and die?

My value will survive!

Cue Sax solo.

p.s. you want self to live throughout the animation and possibly into completion. stay strong.

Apple Swift team undergoes reorganization

Statement from Chris Lattner:

Since Apple launched Swift at WWDC 2014, the Swift team has worked closely with our developer community.  When we made Swift open source and launched we put a lot of effort into defining a strong community structure.  This structure has enabled Apple and the amazingly vibrant Swift community to work together to evolve Swift into a powerful, mature language powering software used by hundreds of millions of people.

I’m happy to announce that Ted Kremenek will be taking over for me as “Project Lead” for the Swift project, managing the administrative and leadership responsibility for  This recognizes the incredible effort he has already been putting into the project, and reflects a decision I’ve made to leave Apple later this month to pursue an opportunity in another space.  This decision wasn’t made lightly, and I want you all to know that I’m still completely committed to Swift.  I plan to remain an active member of the Swift Core Team, as well as a contributor to the swift-evolution mailing list.

Working with many phenomenal teams at Apple to launch Swift has been a unique life experience.  Apple is a truly amazing place to be able to assemble the skills, imagination, and discipline to pull something like this off.  Swift is in great shape today, and Swift 4 will be a really strong release with Ted as the Project Lead.

Note that this isn’t a change to the structure – just to who sits in which role – so we don’t expect it to impact day-to-day operations in the Swift Core Team in any significant way.  Ted and I wanted to let you know what is happening as a part of our commitment to keeping the structure of transparent to our community.


The Swift project is driven by a core team of Apple engineers:

The core team “reviews and helps iterate on language evolution proposals from the community at large, acting as the approver of these proposals. Team members help drive Swift forward in a coherent direction consistent with the goal of creating the best possible general purpose programming language.” They are appointed by the project lead.

Holy War: Type aliases

Kyle Cardoza writes: Erica, Is it considered bad style to typealias OpaquePointer when you have to deal with OpaquePointer values that point to different types? The typealiases make the code read so much nicer…

Using typealiases to create “pseudotypes” (where typealiases essentially duplicate a single  type) neatly organizes your code. I endorse any solution that emphasizes semantics and supports readability. As OpaquePointer is not generic, it doesn’t encapsulate type information the way Array<Int> or Set<String> do:

// Both are typed to OpaquePointer, so nothing concrete
// distinguishes the two roles.
// let p1 = OpaquePointer(unsafeMutableRawPtr1)
// let p2 = OpaquePointer(unsafeMutableRawPtr2)

Building convenience typealiases emphasizes the distinction between otherwise structurally identical uses. This differentiates each use-point and provides built-in “type commentary”:

typealias OpaqueType1Pointer = OpaquePointer
typealias OpaqueType2Pointer = OpaquePointer

let p1: OpaqueType1Pointer = OpaquePointer(rawPtr1)
let p2: OpaqueType2Pointer = OpaquePointer(rawPtr2)

// or, thanks Nil, directly:

let p1 = OpaqueType1Pointer(rawPtr1) 
let p2 = OpaqueType2Pointer(rawPtr2)

You might consider an alternative. If you’re willing to trade off a little overhead against enhanced type safety, you might introduce a simple value type. Wrapping the opaque pointer enables you to use a type-specific initializer. Here’s an extremely rough example of what that might look like:

struct SometypeWrapper {
    let opaque: OpaquePointer
    init(value: Sometype) {
        opaque = OpaquePointer(Unmanaged

What do you think? Good use of type aliases? Bad? Or should you always go with a wrapper? Let me know. Drop a note in the comments or send over a tweet.

Thanks, Mike Ash

Forced Unwrapping URLs

Let me start with a little background. Laptopmini wanted to know why this code wasn’t compiling. Admittedly, Swift’s error messages leave room for improvement. The tl;dr was: he needed to swap the 2nd and 3rd lines of code. This allows both properties to be initialized before the code refers to self.

I immediately fixated on those exclamation points. “Are there any circumstances that these URLs will fail during creation? And if so, don’t you want to control that crash?” Laptop pointed out that there was no circumstance where his URLs would be malformed, and it was perfectly safe to use the exclamation point.

Despite this, his approach bugged my aesthetics. There’s no reason those URLs should be created in that initializer. I figured there were better ways to deal with this, moving URL creation out of the initializer and controlling crash landings with better error messages.

First, I considered extending URL to offer a safer non-optional initializer. The following snippet offers “controlled descent”, providing valuable feedback for any string that cannot be used to construct a URL.

extension URL {
    /// Non-optional initializer with better fail output
    public init(safeString string: String) {
        guard let instance = URL(string: string) else {
            fatalError("Unconstructable URL: \(string)")
        self = instance

This seemed too big a hammer for this problem. Instead, I decided to recommend the same approach with a solution localized to the SocketEndPoint type:

// Returns `URL` with guided fail
public enum SocketEndPoint: String {
    case events = ""
    case live = ""
    public var url: URL {
        guard let url = URL(string: self.rawValue) else {
            fatalError("Unconstructable URL: \(self.rawValue)")
        return url

This approach allows his init code to simplify. Under the updated design, it uses ordinary URLs in the initializer and no exclamation points.

// His initializer
fileprivate init() {
    self.eventSocket = WebSocket(url:
    self.liveSocket = WebSocket(url:
    self.eventSocket.delegate = self
    self.liveSocket.delegate = self

Long story short:

  • String enumerations are handy but SocketEndPoint wasn’t pulling its weight. Its job is to deliver named URLs. It should do that no matter however the type is implemented.  Don’t let types slack off because there’s an “almost there” solution baked into the language.
  • Keep initializers clean and simple.
  • When weighing a universal solution against a simple local one, sometimes it’s best to think small and fix the problem in the immediate context.
  • I considered normal URL construction (returning an Optional) and creating a WebSocket initializer with implicitly unwrapped optionals (public init(url: URL!)This approach offered no real advantages and lost the ability to report which string was malformed. Also, ugly.

You can see a few of approaches I kicked around at this gist.

Dear Erica: Singletons and Static Property Side Effects

Laptopmini writes, “Can you define a ‘get‘ closure for a singleton’s sharedInstance? I have a web socket manager and I’d like it to call ‘connect()‘ any time its instance is fetched”

A basic Swift singleton looks like this:

public final class Singleton {
    public static let shared = Singleton()
    private init() { }

This design creates a class with a single accessible shared instance. The class is marked final, and the initializer is private, ensuring the type cannot be subclassed or instantiated beyond shared.

To introduce side effects, create indirect access to the singleton and add your custom behavior to a getter:

public final class Singleton {
    private static let _shared = Singleton()
    private init() { }
    public static var shared: Singleton {
        get {
            print("side effects here")
            connect() // for example
            return _shared

This works but it’s a little more complicated than it has to be. As a get-only property, you can omit the get syntax. Just move the custom behavior to the top-level var clause, as in the following modification:

public final class Singleton {
    private static let _shared = Singleton()
    private init() { }
    public static var shared: Singleton {
        print("side effects here")
        connect() // for example
        return _shared

Quick summary:

  • Use reference types for singletons.
  • Mark the type final, the instance public, and the initializer private.
  • When naming, prefer the Swiftier shared to the more Objective-C sharedInstance.
  • Create a static getter for any side effects.
  • Omit the get syntax for get-only properties.

Have some thoughts about improving this? As always, drop a note in the comments or tweet me and I’ll tweak.

Rob N has a good point here:

Swift Style vs ProseLint: The Smackdown

ProseLint is great. As I’m writing a book about style and linting, it’s natural to try to lint the book that lints your programming. In using this tool, I’ve encountered some amusing “lint fails” that I’d thought I’d share.

ProseLint vs Nil Coalescing: “hyperbolic.misc ‘`??`’ is hyperbolic.” Winner: Swift Style.

ProseLint vs discussion of Forced Unwwrapping: “leonard.exclamation.30ppm More than 30 ppm of exclamations. Keep them under control.” Winner: ProseLint. Any forced unwrapping, even in a discussion about forced unwrapping, is an obvious fail. Save the kittens, drop the !’s.

ProseLint vs Meaningful Variable Names: “typography.symbols.multiplication_symbol Use the multiplication symbol ×, not the letter x” Winner: Swift Style. As Freud said, sometimes an letter  “x”  is just a letter “x”. (Or was that Groucho Marx? I forget.)

ProseLint vs “Use American English Spelling” rule: “consistency.spelling Inconsistent spelling of ‘color’ (vs. ‘colour’)” Winner: Swift Style. When writing for a global audience, prefer “color” to “colour”. (See? I did it again. — B. Spears)

Winner? Forget the points. It’s ProseLint. This summary doesn’t include the great catches made and fixed, like excessive use of “very”, repeated word detection, etc. Great tool, check it out.

Reducing to Swift sets

A friend asked me, “Is there a better way to reduce to a set than .reduce (Set<String>()) { $0.union(CollectionOfOne($1)) } ?” He was fetching results from an external source and wanting to feed them into a set.

We kicked some ideas back and forth about how this could be implemented. Would he need to query the set before fetching all the items (no) and would his data set be so large that it would be impractical to store the intermediate results into an array before creating a set (also no).

I built a suite of tests, trying out his reduce method, using normal insertion, etc.  I assumed that using a Set initializer would probably be the best approach for a pre-computed array, but it turns out that union and insertion performed better in repeated tests:

timetest("initializer") { //  0.652348856034223
    var x: Set<String> = []
    (1 ... 5_000).forEach { _ in
        x = Set(letters)

timetest("union") { // 0.524669112986885
    var x: Set<String> = []
    (1 ... 5_000).forEach { _ in
        x = x.union(letters)

timetest("insert") { // 0.572339564969297
    var x: Set<String> = []
    (1 ... 5_000).forEach { _ in
        x = []
        letters.forEach ({ x.insert($0) })

timetest("reduce") { //  0.762973523989785
    (1 ... 5_000).forEach { _ in
        var x = letters.reduce(Set<String>()) {

That surprised me since you’d imagine that  init<Source : Sequence where Source.Iterator.Element == Element>(_ sequence: Source) and func union<S : Sequence where S.Iterator.Element == Element>(_ other: S) -> Set<Element> would have similar performance characteristics.

What didn’t surprise me was that trying to create a set on the go cost more than storing intermediate results to an array and then building a set out of them. So long as the array was reasonably limited in size (that is large enough to be non-trivial but not so large that it put a burden on application memory), an intermediate array seems to be the better approach. Set(collectedResults) outperformed insert, formUnion, and reduce/union for non-trivial result sizes.

Unexpected precedence issues with try? and as?

Tim Vermeulen recently wrote on the Swift Evolution list that try? precedence can be unexpected:

if let int = try? mightReturnInt() as? Int {
 print(int) // => Optional(3)

Specifically, he discovered that try?’s precedence is lower than as?’s precedence, so you may have to add parentheses to get the right result.

if let int = (try? mightReturnInt()) as? Int {
    print(int) // => 3

He also found a similar issue with using try? on a throwing-optional-returning scenario:

if let int = try? mightReturnInt() {
    print(int) // => Optional(3)

if let int = (try? mightReturnInt()) ?? nil {
    print(int) // => 3

There’s some magic baked into if let item = item as? T that automatically lifts optionals, which doesn’t yet seem to extend to try?. If you’re running into these situations, consider adding parentheses and nil-coalescing as demonstrated in these examples.

In case you think a throwing-optional scenario is too “out there”, think of a file system request that would throw on an unreadable directory and return nil if a specific file does not exist. Although obscure, it is not unthinkable to combine the two approaches.

My first Cozmo game: Hide and Seek

In my continuing exploration of the Cozmo SDK, I’ve written my first  game. “Hide and Seek” is not particularly complex or challenging. I’m still pretty new to both Python and the SDK tools and my wrapper code is still pretty basic.

“Hide and Seek” goes like this. You place a light cube near Cozmo out of his direct line of sight. He searches until he finds it, picks it up, moves it to a new location, and drops it. He then turns around, with his back to the cube and says “Let’s play again”.

Although this is a first take, I think my wrapper approach remains pretty simple and readable. I’m trying to emphasize learning programming concepts, using Python, which means that Cozmo access needs to be encapsulated and procedural:

# run, cozmo, run
def actions(cozmoLink):
    '''Specify actions for cozmo to run.'''
    # Fetch robot
    coz = Cozmo.robot(cozmoLink)
    coz.say("Hide and seek!")

    # Look for a cube
    if not coz.findACube():
        coz.say("No cube")

    # Found one!
    coz.say("I found a cube")
    coz.takeCube() # Pick it up
    coz.say("I have the cube") = 3, direction = Direction.forward) # Drive
    coz.dropCube() # Place the cube
    coz.turn(degrees = 180) # Turn around
    coz.say("Let's play again")


The most complex concept here is searching for a block (coz.findACube()) and acting on a Boolean return value. I’m not completely in love with how I established this notion. Maybe something more along the lines of “ask to look and find” instead of just “find” would better indicate conditionality.

Under the covers, the Cozmo class now stores both a cube of interest and a list of cubes within view. I’m not sure I’m going to stay with this specific design but this new feature is what allows you to omit mentioning the cube instance in the latter half of the game. I think I probably need to step back and refactor to evolve a Cozmo’s “world” class, to describe what he sees, and better mirror the world in the direct APIs.

Here’s a video of the “Hide and Seek” gameplay:

My immediate goals are to encapsulate all the asynchronous and exception-handling code into very simple call styles. I want to model the world, the robot, and the interactions in a more human-based way, to support simple programming concepts: procedure, state, condition, iteration, and eventually functions.

Even though I’m directly interested in teaching, at the back of my mind, I want to eventually get to the point where I can introduce some emotion programming, which I think is perfect for Cozmo.

I wouldn’t have to start from scratch. There’s some GPL licensed work done in the Facemoji project. Facemoji harvests an emotion dataset, classifies the emotions, and then matches incoming video against the data set. Wouldn’t it be great if Cozmo could react to your face beyond recognition, playing off happiness, sadness, etc?

Buy a book: Swift Style


I’m happy to announce that Swift Style has gone into beta release at  the Pragmatic Bookshelf. My book is now ready for sale as part of their beta program. This program gives you early access to the book’s material as I work on it.

Be part of the writing process. Beta access enables you to offer feedback as I finish writing:

Before a book gets to the final, ready-to-publish state, it normally looks quite rough. It will have hundreds of typos and grammatical errors. It’s likely to have technical errors that would normally get corrected in a final read-through by reviewers. And it’ll certainly look fairly ugly—we don’t do any layout work until just prior to sending a book to the printer, so there will be widows, orphans, text split across page turns and so on.

As you find mistakes or technical errors, if want to argue for or against a style rule, or you’d like to submit an enhancement suggestion,  click the Report Erratum link on the book’s home page. If you have any in-depth feedback (either positive or negative) that goes beyond the scope of the erratum page, drop me an email. Enable notifications so you receive an email whenever the book updates.

Swift Style: Beta Book

Self-Published Books

Thank you for your support!