Archive for the ‘Musings’ Category

If I had my druthers: Swift 2.2, Swift 3.0, ABIs, etc

If I could wave a magic wand, I’d push Swift 3.0 out by a year or even better three years and fix Swift 2 as the standard App Store language (and for Linux, and upcoming Windows) exactly as is, barring a few tweaks and fixes over this time.

[tl;dr summary: Make big breaking changes later and once rather than sooner and multiple times. If a delay allows a single stable language transition, it is to be preferred. Aim for post-3.0 language updates to be additive not transformative.]

Swift 2.2 is a great language. It’s amazing to work in. It offers utility and concepts that Objective-C cannot provide. It pushes iOS and OS X development forward in an important and exciting way, affecting development not just on Apple platforms but wherever Swift touches. From first class structure and enumeration types to protocol oriented programming, Swift 2.2 delivers the goodies.

If you need just one compelling single example, take CGRect: Swift 2.2 lets you expand this essential structure with methods and properties that let you center on a zero origin, or scale and transform, or add math to combine instances. It’s so practically useful that going back to ObjC to work in geometry metaphysically hurts.

Swift 2.2 gets it right in so many ways, that it seems ridiculous to throw it away at the end of the year. A language this good should have a lifetime longer than 8 or 10 months. I’d be really happy if at the WWDC keynote, Tim Cook said, “We got it so right, we’re going to stick with Swift 2, let you build your code for long term use, and make sure the transition to Swift 3 will be perfect.”

The move to Swift 3.0 isn’t just going to be disruptive. It’s going to be traumatic. With its expansive renamification and redesigned core types and APIs, Swift 3 is going to be a tidal wave of retraining and refactoring. And with a list of objectives that didn’t quite make the cut, and a laundry list of of items that should have, Swift 3 just doesn’t have enough time or scope to be perfected.

So why not just push it back?  Let us devs use Swift 2.2, which is terrific, for a few more years and get Swift 3 right the first time?

It’s not as if Swift Evolution needs to be fast paced and hectic. The bikeshedding, the simple natural discussion overhead, the need to foster a courteous open source community means the natural speed of development has taken a huge hit.

These arbitrary “update every year” advances that Apple has bought into are more than a little ridiculous when it comes to firmware and OS updates; for languages it pushes beyond the practical.

Orson Welles promised that Paul Masson would sell no wine before its time. Apple should take a lesson from Welles and ship no language before the follow-up version has properly evolved.

I want to see Apple slow down, take some deep breaths, and seriously consider letting Swift 2.2 come into its own rather than cutting it down after a few months of use.

As it is, I am constantly having to answer “Is it time yet to switch to Swift?” As this breakneck development continues, I’ve been hesitant to recommend jumping aboard the Swift train for simple practical reasons.

I’d be far more confident with my advice if I could see a 2-3 year window with stable code that could benefit from Swift’s modern language features, and a payoff of investment in training and refactoring that won’t have to be re-addressed with each new beta and each new release.

To paraphrase a line from Aesop, slow and steady really does win the language race.

Like my posts? Consider buying a book or two or three. Thanks!

Dipping toes into coworking

As George RR Martin would have put it if his kids were in public school: Summer’s coming. (“A Song of Bored and Cranky”) This Summer, I plan to try to use some coworking spaces to get the heck out of the house and away from the kids for a couple of days a week.

So far, I’ve tried out “eat-working” (Starbucks, Panera, Einsteins), which really doesn’t offer the kind of long-term desk situation I’m looking for, “public-working” at the library, which had iffy chairs and tables and intermittent Internet, and (so far) one commercial day trial, which had great desks, horrible chairs, nice ambience, but a no-talking policy which meant I couldn’t conference, use my phone, or use Siri except by stepping outside. (And absolutely no way to turn up the iTunes volume and shout it out, shout it out loud…)

If you’ve coworked and have any recommendations for what I should be looking for in a good coworking space, please share. I’m not exactly looking for place recommendations (unless you have specific ones to mention) but more to put together a list for myself of what makes a good coworking environment so I can better evaluate what I”m looking at before committing to any monthly or longer contract. I’d appreciate any advice you have to offer.

I’m looking for something fairly local, inexpensive, with good business-level WiFi, comfortable business-level chairs and desks (I can bring in my own lumbar cushion and footstool if needed), safe area, clean bathrooms, nearby shops, a microwave, easy in-and-out, and  daylockers of some sort so I don’t have to carry absolutely everything in and out with me every time I hit the bathroom or go to lunch. I’d also like to be surrounded more by tech folk than marketing folk but I recognize that’s not going to be something I can control.

I will say that while I was remarkably productive on my days out, I was productive in all the wrong ways: I zoomed through my correspondence. I’m now set up beautifully with my calendar and with “Things“. I got nothing done on actual development or real writing work. And I did nothing that needed phones, such as making appointments or checking in on projects. I also found it really hard to take breaks, stretch, and just do the “wander and think” thing.

What kind of work opportunities do you reserve for outside your office? And how do you adapt your workflow to small screens (I have the new MBP with me), strange places, and ergonomic limits?

Thanks in advance for your thoughts.

Fast-tracking Swift reviews

I’d like to see Swift Evolution adopt a couple of styles of fast track reviews. Here’s how they would look.

STYLE ONE: Minor language enhancements AKA “Low hanging fruit”

It would help if the core team could add minor language enhancements without going through a formal proposal process with its normal review overhead. I have now been involved in several reviews that involved API changes that were otherwise unremarkable and primarily motivated by modernizing and style:

To this list, you could add:

Each of these proposals could have proceeded with a simple “any objections” sanity check discussion period rather than a more formal full review. As a another example (now unnecessary), consider the `dynamicType` keyword, which would have required a formal proposal to be modernized into Swift’s lowercase keyword standard. The hallmarks of these changes are:

  • They have limited impact
  • They increase language consistency
  • They are uncontroversial, offering simple, straightforward, and correct changes  that have already passed review in spirit, if not in letter
  • A preponderance of reviews are “+1” rather than in-depth discussions of why the proposal  should or should not be adopted.

I would recommend retaining a change document requirement for these proposals. This would be similar to a brief but formal proposal, that lays out the justification, detail design, and any associated background info for the change. Doing so would provide a historic record of the change and any notes from the team, and be in a form that would support the extraction of key details for use in release notes.

I do not know whether these would need to be grouped and numbered with the normal proposals or placed into their own numbering scheme.

STYLE TWO: Fast tracking viability

Once a draft has been discussed on-list and submitted as a pull request, I’d like to see a biweekly (or even once-a-month) Pull Request Review meeting from the core team where a review groups looks over the current pull-request queue and scores them: recommend closerecommend promoteneeds workdefer past 3.0. This approach:

  • Would offer closure to proposal authors who are otherwise unsure of the viability of their proposals
  • Naturally happens after a significant on-list discussion/pre-review period has already  taken place
  • Would allow the team to weed out proposals with significant issues before entering formal review
  • Would allow on-list reviews to give precedence to only those proposals that make sense both in the time context of Swift 3.0 and its overall design philosophy.

Swift is an opinionated language. This review style would introduce discernment and feedback slightly earlier in the process without stifling on-list discussion.

A few final thoughts

It is a given that Swift 3 is going to be the last opportunity to make large, code-breaking changes to the language. With that constraint, I’d like to see more time and effort go into improving Swift’s fundamentals. Any time, effort, and review that can be better spent getting collections and indices right rather than worrying about colons and casing is, in my opinion, worth a tradeoff in community control.

The natural tension between engagement and coherence requires a balance that serves the entire Swift community. Open evolution processes are, by nature, chaotic. Maintaining a coherent vision for something as complicated as Swift requires coordination and leadership.  That’s why the ultimate responsibility for adopting changes lies with the Swift core team, which establishes the strategic direction of Swift.

I hope by adopting these fast-track review styles that the Swift open source community can better focus on the big updates while making sure that the small details are attended to carefully and thoughtfully without overwhelming the process.

Swift Style: Are you a 4-denter?

Two space indentation seems to be the new craze. “Four space indentation? Are you mad, that’s nearly as bad as tabbing with eight?” is the meme of the moment. (Or, as established in Zoolander, “Two spaces? It’s so hot right now.”)

While two space indentation offers more horizontal space to work, four spaces continues to create an elegant sense of white-space and scope-based horizontal stepping that provides light and easy reading.

(I ignore the three space addicts in this discussion, while acknowledging they do exist. As Mike Ash puts it, “I think three spaces should be, ‘Do not approach. Retreat to a safe distance and call the police as soon as you’re clear.‘” Chris Lattner counters, “I think you under appreciate 3 space indent.  It looks the best, and conclusively settles the tabs vs spaces debate.” coughtrollcough1)

Like my previous colon discussion, Apple answers seem to vary by group. Apple docs, including the Swift Programming Language, consistently use four spaces, enabling clean examples that breathe:

Screen Shot 2016-03-31 at 9.00.40 AM

and the Standard Library group uses 2, following LLVM Coding Standards, which I find a bit claustrophobic. (Thanks, Greg!)

Screen Shot 2016-03-31 at 9.01.39 AM

So I went off to google. First up, I found a 1983 ACM paper by Richard Miara, Ben Schneiderman, and some others called “Program Indentation and Comprehensibility“, which sought to test whether 2-4 spaces were more ideal than 0 or 6 spaces. Unsurprisingly, this premise was born out by their research.

They found that indentation level had a statistically significant effect on comprehension, and optimal indentation fell somewhere between 2 and 4 spaces. As the spacing increased beyond that (6 spaces or more), comprehension decreased.

It’s worth noting that all testing was done: (1) in the 1980’s (2) on 80-column-limit systems, and (3) with choices limited to 0, 2, 4, and 6 spaces. “The level of indentation we tested (0-6 spaces) gave strong results favoring 2 or 4 spaces.” The paper recommends that more indentation levels (0-8 spaces, or nine total levels) be studied in further depth. I’m sure someone got around to it before Starbucks and the MacBook Pro were invented.

In contrast, there’s the Jay Bonci codex (Perlmonks, 2002, “The One True Style of indentation“), a sociological introspection of indentation. Here’s a subset of the Bonci codification that maps spacing choices to internal coding intent.

  • One space – Screw readability. I’m pissed they even make me separate my operators. Perl should be more like Latin.
  • Two spaces – I have my head on straight AND I respect screen real estate.
  • Three spaces – I have a little flair, or a nervous twitch. Or the second disguised as the first. Or you listen to waltz while you code.
  • Four spaces – I read a few standards docs and now I think I’m all spiffy. Vannila (sic) Ice, I know you’re in there.
  • Six spaces – I have agression (sic) issues, and my outlet is machine gunning the space bar
  • Eight spaces – You end every line with a meniachal (sic) “DIE! HAHAHAHAH! DIE! YOUR FRIENDS CANNOT SAVE YOU NOW.”
  • Tabs – I’m a lazy person. I know all of the vi commands by heart. Or you drank the 80’s soda.

In the real world, indentation seems to have settled on two, four, and sadly three space standards. So what’s your indentation style? And why?

1  My personal use of 3-space indentations have almost entirely been predicated on accidental deletion of a member of a 4-space unit, but they have happened.

Like my posts? Consider buying a book or two. Thanks!

Afternoon Whoa: Swift’s guard case =

Bryan Luby asks: “What is your take on using the Swift 2 “guard case” syntax vs using the “~=” expression pattern?” And I was all, aren’t guard cases really for pattern matching associated values like this?

enum Test {case a(Int), b(String)}

let x = Test.a(2)
let y = Test.b("Hello")

guard case Test.a(let value) = x else {
    fatalError("shouldn't fire")
}

guard case Test.b(let value) = x else {
    fatalError("will fire")
}

But no, Bryan was talking about guard case indices = index else { return nil }, which works like this:

let foo = "abcdef".characters
let bar = "abcdefghij".characters
guard case foo.indices = foo.startIndex else {fatalError("won't fail")}
guard case foo.indices = bar.endIndex.predecessor() else {fatalError("fails")}

It’s a really weird way of testing the rhs value against the pattern on the lhs. Compare and contrast with

guard indices ~= index else { return nil }

After thinking about this for a bit:

  1. That is quite cool
  2. I don’t think I like it at all.

The readability is awful. And, I don’t think a large part of the Swift community is aware of or uses this pattern. Going by the principle of “code is more often read than written” (not to mention the “principle of least astonishment”), I’d stick with the pattern matching operator over guard case.

Agree? Disagree? Comment, tweet, or email. And thank you Bryan because I love discovering stuff like this.

Zachary Waldowski tweets: “if/guard/for/while case is the built-in way, whereas ~= is essentially an implementation detail. :/”. Maybe so but I don’t think that make the code any prettier or easier to read. He replies: “Honestly, I couldn’t tell you; I think “if case” reads better, but my coworkers say I’m nuts.”

The push-pin principle

I’ve written before on my desire to reconstitute a weak reference in completion handlers, something along the lines of :

guard bind self else { return }

John Estropia writes,

About the weak-strong dance, it’s currently perfectly fine to do

guard let `self` = self else {return}; self.doSomething

We actually made this a rule in our team.

I feel all kinds of odd about this approach, which rests on the notion of ensuring a strong reference to self that persists through the handler’s scope. Once you pass through the guard, the self reference will be valid for that lifetime. What do you think of this work-around, which of course would be improved merely by renaming `self`?

guard let strongSelfReference = self else {return}
self.doSomething

(Mike Ash offered another solution that works in existing Swift that I encourage you to peek at. His approach registers items and invokes callbacks.)

Looking forward in terms of Swift Evolution, I’ve recommended enhancements along the lines of:

// self-shadow a weak item
guard bind self else {return}
self.doSomething

//and an equivalent for a symbol that doesn't shadow itself
guard bind symbol = someInstance.blah.weakReference else {return}
symbol.doSomething

But don’t hold your breath waiting for bind to appear in Swift. I find `bind` clearer than overloading a constant or variable declaration. It’s garnered no supporters and I’ve reluctantly been letting it go. (Although not so quickly that I didn’t first include it in this post as a last farewell.)

Others suggested integrating a guard into the initial weak capture. Unfortunately [guard self] doesn’t express how scope should exit. Should it return? Throw? Print an error? A separate guard statement is more verbose but it places explicit control in the hands of the developer on exit strategies.

Alternatively, you could introduce a weakstrong capture specifier that’s limited to -> Void closures (thanks Davide De Franceschi and Mike Ash)

[weakstrong self] in

Evan Maloney’s Allow using optional binding to upgrade `self` from a weak to strong reference proposal recommends allowing shadowing self without backticks.

[weak self] result in
guard let self = self else { return }

How would you redesign things? What do you think of the pushpin? Does Swift need to change? If so, how?

Swift First Labels: Bring ’em back

Today Joe Groff asked whether the first parameter in a function declaration should follow the same rules as the remaining parameters.

Our accepted naming guidelines have embraced first argument labels for functions and methods. This weakens our justification for making the first parameter declaration in a `func` declaration behave differently from the others, implicitly being unlabeled. It seems pretty clear to me we should make all of the parameter declarations behave uniformly:

func foo(x: Int, y: Int) // Should declare foo(x:y:)

instead of foo(_:y:)

func foo(_ x: Int, y: Int) // Explicitly declares foo(_:y:)

This would also make `init` and `func` parameters behave consistently, which is nice. There may still be hope for our keyword argument rules to one day be shorter than the Smalltalk spec…

I endorse this. Swift’s guiding principles are clarity, concision, and consistency. The history of leading-labels from Swift 1 to Swift 2 and now to Swift 3 showcases a place where language design swerved to better serve Cocoa/Objective-C standards and now returns to  the emerging needs of a new and distinct language.

Swift supports Objective-C interoperation but the language is not Objective-C. There’s still a great need to support, bridge to, and interact with legacy code but that support should not drive Swift’s  design.

A natural turbulence exists between Swift’s design principles and the existing body and APIs of Cocoa code. From error handling to type safety, method signatures to core types, Swift needs to focus more on being Swift and less on feeling familiar to transitioning developers, especially as more users hop onboard from non-Apple platforms and languages.

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.

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.

Swift bracing

By convention, Swift embraces the “One Truce Brace Style” or 1TBS as its standard for laying out code. A variation of K&R bracing, 1TBS adopts the following features:

  • Opening braces appear at the end of the statement that establishes a clause
  • Else statements appear between paired close and open braces
  • All clauses are braced. Single-line clauses use mandatory bracing, just like multi-line clauses. Bracing ensures that all code line insertions will be safely added, and cannot break the intended flow.

A typical Swift if-statement looks like this, incorporating the 1TBS features listed above.

if let value = key {
   // ...do something
} else {
   // ...do something else
}

Xcode automatically styles code using 1TBS and Apple’s sample code and standard library use it as well. Despite this, you can easily override Xcode to incorporate Allman style, also known as “BSD style”.

Unlike 1TBS, Swift Allman wraps its opening brace so there’s always a clear visual path between opening and closing braces. Here is the Allman adaptation of the if-statement you saw previously.

if let value = key
{
   // ...do something
}
else
{
   // ...do something else
}

You can easily trace each opening brace to its closing partner and the else statement sits on its own line.

I mention Allman because Swift is not a language demanding vertical compactness. Clarity and safety should always win over succinct form.  Apple writes,

Clarity is more important than brevity. Although Swift code can be compact, it is a non-goal to enable the smallest possible code with the fewest characters. Brevity in Swift code, where it occurs, is a side-effect of the strong type system and features that naturally reduce boilerplate.

It’s a shame then that the language has adopted 1TBS over Allman when the latter exposes scope so beautifully and the former can be quite hard to follow, especially with respect to complex declarations that include external and internal labels, default values, and other complicating features:

Compare this example in 1TBS:

public extension Contextualizable {
    public func BuildContextError(
        items: Any...,
        file: String = (__FILE__ as NSString).lastPathComponent,
        function: String = __FUNCTION__,
        line: Int = __LINE__
        ) -> CoreError {
        
            let reasons = items.map({"\($0)"}).joinWithSeparator(", ")
            let context = "\(function):\(self.dynamicType):\(file):\(line) "
        
            return CoreError(reasons, context)
    }
}

with its Allman counterpart.

public extension Contextualizable 
{
    public func BuildContextError(
        items: Any...,
        file: String = (__FILE__ as NSString).lastPathComponent,
        function: String = __FUNCTION__,
        line: Int = __LINE__
        ) -> CoreError 
    {
        
        let reasons = items.map({"\($0)"}).joinWithSeparator(", ")
        let context = "\(function):\(self.dynamicType):\(file):\(line) "
        
        return CoreError(reasons, context)
    }
}

The Allman example simplifies the layout, making it far clearer where each declaration (Contextualizable, and BuildContextError) begin and end.

Swift’s worst bracing sin actually appears in switch statements (although get and set for properties are also not without sin). Left-aligned cases and defaults make its switches a horror to scan.

switch item {
case "B", "C", "D": print("Hello")
default: print("World")
}

Bracing also plays an in-line role due to Swift’s functional programming support. An in-line map can appear with or without parentheses (I use the Rule of Kevin, which supports parens) and with or without in-brace padding.

This example skips that padding:

items
    .map({"\($0)"})
    .joinWithSeparator(", ")

This example uses padding:

items
    .map({ "\($0)" })
    .joinWithSeparator(", ")

I am currently leaning (slightly) towards the padding side of things although my personal style to date has not incorporated it. This example also uses indented dot-prefixed fluent chaining, although that’s probably a better subject for another post.