Archive for February, 2016

Xcode 7.3 updates playground rendering

Screen Shot 2016-02-09 at 2.52.52 PM

Notice anything different in rendered playground docs between Xcode 7.2 and the 7.3 beta? The new style uses a lovely serif font and has dropped gray backgrounds. (If you’re looking to extend custom styling even further, drop a radar at bugreport.apple.com. You won’t be alone.)

Jack Lawrence writes that the new style is due to a complete refactor from built-in web views and CSS to native Core Text rendered goodness. The updated playground rendering adds new markup keywords:

  • - experiment: to suggest ways to interact with the playground’s Swift code and prompt interaction with live views
  • - note: that adds related information and tips that augment reading through the primary document
  • - important: for cautions and warnings

He sent along an example of the experiment keyword rendering in Swift standard lib playground:

CazmkCLUEAE5KRD

A few more:

Screen Shot 2016-02-09 at 3.47.29 PM

The trouble with argument labels: some thoughts

Debate has been raging for weeks about the scope and content of guidance to include in Apple’s API guidelines, particularly when it comes to labeling arguments in methods and functions.

A Swift signature consists of a method name followed by a series of argument labels, parameter name, and types, and concludes with a return type.

methodName(argumentLabel parameterName: parameterType, ...) -> returnType

Swift 2 adopted a convention that follows Objective-C style, where the Swift first argument label is omitted by default and its information is subsumed into the method name.  In nearly every case, argument labels followed three simple rules:

  • Skip argument labels for a method or function’s first parameter
  • Use argument labels for a method or function’s subsequent parameters
  • Require argument labels for initializers

These Objective-C-based language defaults enable devs to structure readable code sentences from API calls, for example:

myHandle.readFrom(file, ofType: utiSpecifier)

reads as “read from file of type utiSpecifier“. Retaining this kind of  meaningful sentence structure has been a high priority for the Swift team.

The challenges of the Objective-C Legacy

Despite strong influences to the contrary, Swift is not Objective-C and it’s becoming less Objective-C with every update. Language evolution means that Objective-C-based naming rules must be re-considered in the light of certain Swift realities.

Many methods are overloaded. A login method may take a credential argument or a username/password pair:

login(credential: myCredential)
login(username: "bob", password: "123")

While you could use loginWithCredential(_) and loginWithUsername(_, password), these renamed forms are less clear. Both alternatives use with, an indication that there’s something fundamentally askew in your naming choices.

“With” better describes use from a call site rather than method or function semantics. So when using “with” as your go-to preposition, carefully consider whether you should use first argument labels or whether other more meaningful prepositions could apply.

Many Swift functions are fundamentally different from Objective-C instance methods. Calls like

min(number1, number2)
zip(sequence1, sequence2)

offer no intrinsic “sentence”. They are operations on arguments that are essentially anonymous. They provide no useful way to distinguish one from another. Apple calls these “peered” arguments.

Peers also pop up in method calls, when there’s a strong semantic connection between parameters. These next examples are peered but in a non-anonymous fashion: (x, y) and (red, green, blue, alpha).

mySprite.moveTo(x: newXLocation, y: newYLocation)
view.fadeToBackgroundColor(red: r, green: g, blue: b, alpha: a)

In each case, you could move the first argument from the label to the method name (moveToX(_, y:)) but you’d lose your core peer grouping for the sake of Objective-C conventionality.

Some Swift methods are more initializer-like than method like. A similar issue occurs when building factory-style methods that create new instances outside of normal Swift initializer construction.

Vehicle.buildStandardBus(type: .School, color: .Yellow, district: .CherryCreek)

The arguments for this call aren’t “peers”. They consist of unrelated elements intended to initialize fields. Despite that, their call pattern better follows a fully-specified initializer pattern than an Objective-C-like version. Once again, it makes sense to use first argument labels.

Providing Guidance

Apple at this point has three ways it can go:

  • It can stick to Objective-C style guidance, providing a list of exceptions where you should use first labels overrides;
  • It can use Label-style guidance, recommending argument labels in all cases, with a long list of exceptions where you should omit first labels and pick up context from the base name; or
  • It can entirely drop guidance on label naming, allowing overrides at the developer’s discretion.

After weeks of discussion about whether parameters describe instance attributes, whether parameters are semantically distinct from base name actions, how to interpret whether prepositions modify first arguments, and so forth, I’m now leaning towards option three.

There’s a scenario I call “going Hungarian“, by which I mean introducing rules that are so complex and overspecified that one loses sight of the basic principles of keep your naming clean, short, readable, and consistent. I’m afraid that the currently proposed rules have, in fact, gone Hungarian and Apple would be better served by stepping back and dropping the issue.

This was not my opinion going into the discussion. But after reading extensively through the ongoing discussions, the concerns, the tweaks, and the minutia that keep being brought up, I’ve come to the conclusion that Swift legitimately breaks the Objective-C paradigm. There are sufficient and valid reasons to drop the “one size fits all don’t use first arguments” rule under Swift’s new reimagined type system and module interfaces.

I’m not saying change the way Swift defaults its argument labels or modify its implementation. I like it exactly the way it is. I’m saying I now support dropping the effort to define when and where to use first argument labels and not to.

This opinion will not change the ongoing effort to modernize Foundation APIs, and convert familiar calls to more Swift-like ones. I’m just trying to say that the developer-facing API guidance should perhaps step back and do less rather than come up with rules (no matter how parsimonious) about whether and when to use first argument labels and when not to.

My proposed replacement rule for this whole mess is this: “Skip argument labels for a method or function’s first parameter unless it makes more sense not to.” The choice is left as an exercise for the programmer, who should use their own judgement. So long as the result is clean, short, readable, and consistent, I’m good with it.

Disagree? Let me know why. Drop a comment, a tweet, or an email.

Update: A new set of proposed rules from Apple:

A. Try to form a grammatical phrase including the first argument and describing the primary semantics at the call site.

B. The first argument gets a label when and only when:

  1. It does not form part of a grammatical phrase describing the primary semantics. For example,
     x.dismiss(animated: y)
    

    [more examples needed] Note that parameters with defaults never describe the primary semantics. so are always labeled.

     func invert(options options: SomeOptionSet = []) // yes
     func invert(_ options: SomeOptionSet = [])       // no
    
  2. The method is a factory method; such calls should mirror initializers, with no preposition. For example,
     let x = UIColor(red: r, green: g, blue: b)
     let y = monitor.makeColor(red: r, green: g, blue: b)
    
  3. It is part of a prepositional phrase

    a. The label normally starts with the preposition. For example,

       x.move(from: a, to: b)
       x.loadValues(forKeys: ["fox", "box", "lox"])
    

    b. …unless the preposition would break a very tight association between parameters:

       x.moveTo(x: a, y: b)
    

    [encourage grouping parameters into higher-level concepts, e.g. Point, in these cases]

Monetizing while staying the “Good Guys”: the Tao of Red Herring

Copyright Blue Ox. Do not reproduce without permission.

Copyright Blue Ox. Do not reproduce without permission.

Red Herring (Free with IAPs) is one of my favorite iOS games. It’s one of the few single-device iOS games out there that plays better with groups of people than solo. My kids and I regularly gather round an iPad, launch Red Herring, and share time puzzling out the latest daily challenge and game packs.

It couldn’t be simpler: sixteen words and three unknown categories. It’s up to you to figure out how to group those words together leaving four stray red herring “spoilers” that may include words that look like they should fit but don’t actually belong, like “spine”, “bone”, “skin”, and “heart” in the example at the top of this post. The puzzles are tricky, silly, funny, and demanding.

Each game typically takes a few minutes, although a really tough board may last as long as a quarter hour or more. Fan sites have sprung up that offer cheats and solutions, a testament to how loyal and rabid this game’s fanbase can be.

Red Herring is from the creator of 7 Little Words, Moxie, Monkey Wrench, and a few other apps, all aimed at a family-friendly audience. I first wrote about Red Herring a couple of years ago, finding it to be fun and engaging. Last week, I had the opportunity to sit down and talk with Joe Jordan of Blue Ox. We discussed what it takes to grow and retain this kind of loyal customer base and provide a constant stream of creative, one-of-a-kind puzzles.

Blue Ox’s offerings use a standardized model: they include a trial pack to get users hooked, daily free puzzles that acts as maintenance doses, and budget-friendly IAP puzzle packs. Unlike King’s Candy Crush series, Blue Ox’s free users never get to a point where puzzles become impassable or the game sets up the proposition: “Pay us or stop playing.”

Jordan assured me that Blue Ox treasures its free users. “The potential marketing exposure is tremendous. The more they play, the more they’ll tell their friends about it and the more they feel a kinship with us and our games,” he said. That balance between free games and paid makes it easy to transition from free customer to revenue stream. For me, it’s when we’re out for Family Game Night and I want to grab a big set of puzzles to work on. The packs aren’t expensive and they offer a solid game “hang time”.

“We feel very strongly about the value proposition, giving people a good value,” Jordan said. “We’re always happy to have users continue to play, even when they’re just playing the free one.” It’s a philosophy that started with founder and owner Chris York. “Even in internal discussions, he’s always got the viewpoint that we love the customers who only play our daily games and never buy anything from us. They’re always a positive thing and not a drag.”

From a developer’s point of view, Blue Ox’s “virtuous circle” is aspirational. “Our way of approaching customers and potential customers is to give them enough benefit to support us and feel good about what they’re giving money to, the game that they’re a part of, and they like to talk to other people and they perpetuate that forward.”

The IAP becomes a rewarding gratification rather than a game-cheat to keep moving forward. Free daily games ensure that each IAP pack is a positive choice, not a shake-down.

Maintaining the quality of those packs is another business necessity. Each one is hand crafted, typically by professional crossword puzzle designers. Blue Ox has built a network of game authors over time. They started with a few crossword experts and branched out using word-of-mouth recommendations to create an extended team of contractors.

“Our first puzzle writer outside the company was a gentleman in Wisconsin named Ray Hamel. He’s a trivia guru and he brought that to bear on 7 Little Words and was one of the first creators working on Red Herring puzzles. We also have Sarah Hayes, who has written a ton of puzzles for us who is one of the top UK crossword puzzle writers.”

(Hayes also holds the world record for running a marathon while dressed as a beer bottle. The record applies across all bottle types, not just beer.)

Creating the right purchasable content for your game can make or break your application. “We contract with new writers for a small puzzle group to get a sense of what they can do and like to do. It gives a sense of the kind of puzzles they come up with.” When they find the right fit, they expand the contracts to larger batches. Red Herring puzzles are typically purchased in groups and they can take a long time to perfect. “It can be a painstaking process, going back and forth until it’s just right.”

A Red Herring puzzle has to be “unexpected, with relationships among all the different elements of the puzzles,” Jordan said. “We love misdirection: among the categories and between the categories and the red herrings. It has to be more than just, say, the position of a letter within a word or the number of letters that make up the word. There should be a deeper connection of the puzzle elements.”

I asked Jordan what makes a really good puzzle, and he provided several examples. About the puzzle at the top of this post, he wrote, “It is not complicated but it is elegant.”

And this next one? You might not expect to find Macaroni as a Penguin species or Fuseli as a red herring. “This puzzle has nice, discrete categories that require a certain amount of trivia knowledge (while avoiding esoterica). The fusilli/fuseli misdirection is somewhat rare – we’re not trying “gotcha” trickery – but it seems like it works here.”

Copyright Blue Ox. Do not reproduce without permission.

Copyright Blue Ox. Do not reproduce without permission.

Playing with sounds and word structure is another Red Herring trademark, as you see in the following example. “I’m a sucker for puzzles of this type, and I don’t see them enough,” Jordan says.

Copyright Blue Ox. Do not reproduce without permission.

Copyright Blue Ox. Do not reproduce without permission.

Here’s another of his favorites. Although the Jazz Greats may seem a little obvious, the Arthur Dent (Hitchhikers’s Guide to the Galaxy) and cat’s lives twists add a lovely resonance to the puzzle.

Copyright Blue Ox. Do not reproduce without permission.

Copyright Blue Ox. Do not reproduce without permission.

(There are just seven hills of Rome if you were wondering.)

From a programming point of view, there’s almost nothing in Red Herring that a competent coder couldn’t put out with a few weeks of effort and testing. The secret to its success isn’t its GUI or its graphics. Like the best of games, it’s a gateway to a larger experience. The solid puzzles behind the game are the basis of that experience.

Between its respectful balance of free-and-paid elements, and its commitment to ensuring high-quality puzzles, Blue Ox has evolved from a one-man effort to nearly a dozen employees servicing a core family of applications. If you’re starting your own games business, there are a lot worse business models you could follow and few that get it right more than this.

Recent Swift.org updates

I tweeted about these, but am adding a quick post for anyone who missed my timeline:

Swift Resilience conversation commences

Jordan Rose just posted the following on Swift-Evolution, in reference to the new Library Evolution Support in Swift (“Resilience”) document. The RFC requests comment feedback only and will not go through the Swift Evolution proposal process.

Hi, swift-evolution. We’ve been making references for a while to “resilience” as a cornerstone of the Swift 3.0 work, the collection of features that allows a library to evolve over time while maintaining binary compatibility. Among other things, this is necessary if we want to stop bundling the Swift standard library with any app that uses Swift, a noted complaint from iOS developers. 🙂

If you’re wondering what this is all about, take a look at the prologue for the design document:

One of Swift’s primary design goals is to allow efficient execution of code without sacrificing load-time abstraction of implementation.

Abstraction of implementation means that code correctly written against a published interface will correctly function when the underlying implementation changes to anything which still satisfies the original interface. There are many potential reasons to provide this sort of abstraction. Apple’s primary interest is in making it easy and painless for our internal and external developers to improve the ecosystem of Apple products by creating good and secure programs and libraries; subtle deployment problems and/or unnecessary dependencies on the behavior of our implementations would work against these goals.

Our current design in Swift is to provide opt-out load-time abstraction of implementation for all language features. Alone, this would either incur unacceptable cost or force widespread opting-out of abstraction. We intend to mitigate this primarily by designing the language and its implementation to minimize unnecessary and unintended abstraction:

  • Avoiding unnecessary language guarantees and taking advantage of that flexibility to limit load-time costs.
  • Within the domain that defines an entity, all the details of its implementation are available.
  • When entities are not exposed outside their defining module, their implementation is not constrained.
  • By default, entities are not exposed outside their defining modules. This is independently desirable to reduce accidental API surface area, but happens to also interact well with the performance design.

This last point is a specific case of a general tenet of Swift: the default behavior is safe. Where possible, choices made when an entity is first published should not limit its evolution in the future.

When your client demands Swift

Every day, more and more developers are being hired based on their Swift skills. Apple is committed to Swift and Swift is the future. Not a day goes by without some developer wandering by for Swift peer support with “I have to use Swift” because it’s in the contract.

I have shipped only one Swift app for live app store sale and I absolutely love Swift. Everything else remains in Objective-C.  And, yes, it’s painful to move back and forth between languages. As my brain trains for Swift, my Objective-C reflexes are taking a big hit.

Swift, despite migration support and ever increasing stability of language fundamentals, is not stable or will be for a while to come. So how do you break the news to your client, your boss, or that new guy on your team who saw a few WWDC videos that Swift is better suited for a long-term investment than short-term development tasks?

From a smart manager’s point of view, existing code bases, a known stable development path, and a pool of trained developers is more valuable than a scary new language still in development. The lower the risk of failure the better: deadlines are everything when it comes to bonuses, promotions, and job stability. When you have a stable Objective-C code base, why risk your credibility, your job, and your career for an unstable language and API? Experienced managers are the easy sell.

But more and more, people are coming to me and saying, “It’s next to impossible to explain this and sell Objective-C inside any large group or corporation. They look at you as if you’re crazy. Apple says Swift is now. They don’t get the push back.” Apple’s message of “Swift now. Swift for production” is becoming a big issue for developers.

Unless you can express a strong message of investment, stability, risk, and reward you’re going to be in trouble. I’m not saying “Don’t develop in Swift.” For many developers, the language benefits outweigh the refactoring costs that will be incurred over the next few years. It’s the people who don’t see the full picture and timeline that are and will be struggling, the ones jumping in without properly seeing warning signs.

It takes a good six months or so to retrain your brain into Swift development patterns. It will take several more years for the language to stabilize. When you think “Swift”, you shouldn’t be thinking quick-hit-then-walk-away projects. A Swift project means a long term commitment, unless you never plan to re-use any source code, fix any bugs, or provide any upgrades to your apps.

This isn’t the first time the industry has met this issue: think about how C# developed over its first decade. I’m told that many programmers found little projects, worked through them, and gradually built libraries and codebases to minimize maintenance costs over time. Now, as then, training and acquiring developers in anticipation of language stability is and was a challenge.

It comes down to this. If someone is pushing hard for Swift for full apps or critical production code, make sure they know the commitment they’re buying into with associated migration and core refactoring costs, such. Otherwise, Objective-C is still, and will continue, delivering product.

Thanks Mike Prenez-Isbell, Director of Mobile for Univision Television, and the other unnamed developers who spent time chatting with me about this topic.

Naming your Swift Packages

So, in cleaning up a little of my massive backlog of Swift code packs, I decided to take advantage of the Swift Package Manager and put a few things up on github. Which I did.

It was only after that that I realized what a total mess I made of things by naming them in what I perceived at the time to be a logical, sensible way.

Package names need to be clear and specific, yes, but they should avoid terms that will overlap because when you have a package called SwiftString and every Bob, Jane, and Harry also has a package called SwiftString, name collisions are inevitable.

Your SwiftString.doSomethingMeaningfulWithAString() is indistinguishable from everyone else’s SwiftString.doSomethingMeaningfulWithAString(). At this time there is no built-in way that I know of how to deal with module name collisions.

Future solutions might include some way to introduce further namespacing. For example, the Package declaration syntax might add an origin:

import PackageDescription

let package = Package(
    name: "SwiftString"
    origin: "com.sadun"
)

With this, you could avoid name conflicts with

import com.sadun.SwiftString
import com.LeeJason.SwiftString
and
com.sadun.SwiftString.doSomethingMeaningfulWithAString()

For obvious reasons, this could get a little annoying, although if you only import one of the two SwiftString packages, you wouldn’t have to go nearly that far with the disambiguation.

At this time, there aren’t public, blessed, or official repositories of SPM packages but you know this is going to self-organize fairly soon if history is an example. Making sure there’s a clear way to use multiple, potentially overlapping packages will be a good thing.

And, until then, prefer SadunSwiftString to SwiftString and avoid the issue from the start.

SE-0005 The one Swift Evolution proposal you’ll want to know about

SE-0005 is undergoing public review until the 5th of February. It proposes to automatically convert the way Swift imports Objective-C sourced names.

This proposal describes how we can improve Swift’s “Clang Importer”, which is responsible for mapping C and Objective-C APIs into Swift, to translate the names of Objective-C functions, types, methods, properties, etc. into names that more closely align with the Swift API Design Guidelines being developed as part of Swift 3. Our approach focuses on the differences between the Objective-C Coding Guidelines for Cocoa and the Swift API Design Guidelines, using some simple linguistic analysis to aid the automatic translation from Objective-C names to more “Swifty” names.

Cocoa knowledge capital is hard earned, and a fundamental tool for Apple dev work. I’m not convinced that developers will welcome widespread API adjustments that may incur costs in code review, error detection, maintenance as well as the production of new code. Here is Nate Cook’s take. If you work in Cocoa, I encourage you to take the time to carefully read his write-up.

The Swift project rolls out continuous integration

Our CI system is powered by Jenkins. For Apple’s platforms it builds and runs tests for OS X and the iOS simulator. For Linux it builds and runs tests for Ubuntu 14.04 and Ubuntu 15.10 (both for x86_64). In addition to using it for testing active branches, the CI system also produces the snapshots that are available for download from Swift.org.

CI is not only a powerful tool for monitoring the health of the Swift project, but can also be used as a part of reviewing changes before they land. To facilitate this, we have integrated testing within pull requests, allowing testing to occur before commits are made and without destabilizing the master branch. The results will be posted inline within the pull request. When someone makes a change that breaks a build, they will automatically be notified via email.

More details at the Swift.org blog.