Archive for the ‘Books’ Category

objc App Architecture by Eidhof, Gallagher, and Kugler

The objc.io folk were kind enough to let me peek at their latest book, which provides an overview of iOS application design patterns in Swift. Anyone working in production code will be well served by keeping on top of the current art in these patterns.

The book introduces you to both the familiar (Model View Controller, better known as MVC and Model-View-ViewModel-Coordinator or MVVC) as well as less common architectures, which include Model-View-Controller+ViewState, ModelAdapter-ViewBinder, and Elm.  The latter group provides intriguing ways to establish view state and construction and communicate with your semantic model.

After an overview chapter, which explains and motivates each pattern, following chapters focus on exploring a single pattern. (There’s also a separate networking chapter that follows onto MVC and MVVC.) The authors carefully explain how you can incorporate each pattern into your code, considering design and testing, as well as related tasks like persistence. There are plentiful code examples and discussion that offer insights into each pattern’s benefits.

I have not had a chance to fully read the book yet, but what I’ve read has been clear and thoughtful. And yes, there are plenty of examples that tie back to RxSwift.

The book is extremely practical and sure to be of value to serious coders. It’s available from the objc.io site, priced at $49 for the basic eBook or paperback, or $99 which adds seven hours of in-depth video with live coding examples.

Black Friday Sale: Swift Style with a Discount

Happy Thanksgiving Week Everyone!

If you’ve been wanting to pick up an e-copy of Swift Style, there isn’t a better time. Starting tomorrow 11/22 through Friday 12/1, the book is on sale for 40% off. Use this coupon code turkeysale2017 to claim the discount!

So travel safely over the holidays, pick up some great reading, and accept my gratitude for being part of this amazing community.

Update: The PragProg website has been unresponsive. Brian MacDonald writes: “[W]e’re sorry about the delay. The sale runs until December 1, so feel free to check back in a little while.”

Book: Year of No Clutter

Year of No Clutter (Amazon, $9.99) felt like an aptly inspirational title to help motivate me to trim down my house. Like all techies and moms, I am surrounded by outdated equipment (that is occasionally useful) and boxes of “precious” artwork by my “artistically gifted” children, including single crayon scribbles on a page (post modernism) and several thousand RCA cables.

My kids lean towards hoarder tendencies. (“No, you can’t possibly throw that away. I drew it for you!” and “I won that precious partially-destroyed plastic trinket by playing carnival games all day!”). These I must fight with action, as reason goes only so far.

For me, I often lack the time to sort, organize, and toss my things that have become outdated, especially when there’s a real cost to replacing them when they’re eventually needed. (Quick, how many Firewire cables do you own? 30-pin iPod cables? I have too many, but sorting and disposing is hard.)

My go-to solution has long been to put things into boxes and then move them downstairs into the crawlspace. From “memory boxes” to “stuff I don’t use any more”, it’s become a desperate habit of clearing out space.

If I could, I’d go on a rampage throwing things out. The physical and time commitments to make this happen have been overwhelmingly daunting.

Schaub’s book reflects a slightly contrasting reality in that she’s taking on a different kind of clutter. Her Hell Room(TM) represented a “disposophobic” reality, of her well intentioned safety net. She freely calls it a “giant ridiculous mess”. It was stuffed both with items of potential use and necessary memory.  Each hoarded item had a history, and a story, and a connection to her life.

Her memoir offers an amusing tale of the steps in letting go. It’s a record of catharsis and finding the things that actually matter. If you’ve ever looked at a pile of ancient soy sauce packets, trying to decide whether to organize them or toss them, her story will resonate with your experience.

The most interesting thing about the book are the discoveries, where removing surface levels of clutter revealed real treasures and memories, allowing them the priorities they deserved. From family silver to handwritten letters, decluttering has a tendency to hit us in the emotions.

Throughout, Shaub scatters useful little charts and how-to’s. Things you use on a regular basis should have a place to live, and a regimen to restore it to that place after use:

In sum, the book is a conglomeration of reminiscences, self-reflection, how-to, and coaching. There are some delightfully amusing bits and some parts that kind of slog. I particularly enjoyed the section on “The Weirdest Things I Own”. I enjoyed it as a “library read” but I don’t know if I’d purchase it for re-reading.

I probably won’t ever match my own Mom’s ideal of “When in doubt, throw it out”, but the more control I take over our clutter, the better we’ve been able to function as a family.  I want to own things, not have my things own me.

Swift Style: WWDC Sale

Celebrate style in a half shell during WWDC week!

Pick up a copy of Swift Style with a nice discount. The ebook will be 25% off the normal price during WWDC. Use the coupon code Swift_WWDC_2017 at checkout to apply this dub-dub discount to your purchase of the Swift Style ebook at Pragmatic Programmers. (If you encounter any problems during checkout, contact support@pragprog.com.)

Thank you for reading my blog and supporting me and my books!

Update: the discount is already live. You don’t have to wait until next week:

Swift Terms: arguments, parameters, and labels

Help me refine some terminology.

Start with this code snippet:

func foo(with a: Int) -> Int { return a }

You use arguments at call sites and parameters in declarations. This example function defines one parameter that accepts one argument from the call site, e.g. foo(with: 2). 

Apple’s Swift Programming Language book uses this approach:

Use func to declare a function. Call a function by following its name with a list of arguments in parentheses. Use -> to separate the parameter names and types from the function’s return type.

The mighty Wikipedia writes:

The term parameter (sometimes called formal parameter) is often used to refer to the variable as found in the function definition, while argument (sometimes called actual parameter) refers to the actual input passed.

The Swift grammar lays out the external and local differentiation available to parameter declarations:

parameter → external-parameter-name local-parameter-name type-annotation default-argument-clause

Like Apple, I use label instead of name to refer to a parameter’s API-facing component outside of the grammar. The Swift Programming Languages refers to these as a custom argument label, naming it from the consumption POV. Apple writes:

By default, functions use their parameter names as labels for their arguments. Write a custom argument label before the parameter name, or write _ to use no argument label.

I generally call it a label or an external label instead. I often use parameter here (external parameter label, for example), especially when talking about the declaration. I don’t think there’s any real harm in doing so.

In this example, the parameter’s local or internal name is a. Some developers also call it the local or internal variable name. I find that word overloaded in meaning. Swift differentiates constants and variables and does not permit variables in function signatures.

I don’t have any problem calling it an internal argument name either because it’s the name given to the argument passed to the function or method. This seems slightly out of sync with SPL standards and practices. What do you think?

The problem with macOS and Drawing

Trying to write cross-platform code for drawing routines is ridiculously frustrating. It’s never just a matter of creating cross-platform type aliases. UIColor and NSColor are cousins, not brothers. UIBezierPath and NSBezierPath are slightly more distantly related, especially when it comes to adding curves and retrieving an underlying cgPath.

Although a lot of tech debuts on Cocoa, it often gets refined in Cocoa Touch. That refinement doesn’t prioritize cross-platform development, so the “second time, better design” features that leap into iOS land are hard to support with a single code-base. (And yes, I’m looking at you layout constraints with their different dictionary types for metrics.)

Starting last year, UIKit drawing really improved. It already had several advantages over Cocoa drawing, but last year’s update pushed the APIs to a new level.

NSImage has its  init(size:flipped:drawingHandler:) initializer (introduced in 10.8). in iOS 10, UIImage adopted and refined that closure-based drawing approach to UIGraphicsImageRendererUIGraphicsImageRendererFormat, etc. A renderer can return an image or PNG/JPEG data. Very handy, very convenient, wide-color aware, nifty. And it phases out a lot of home-built solutions that devs had been using to get exactly those results.

The new features are not fully refined. For example, there isn’t a single doc comment across the entire feature suite. Which, you know, sigh. But the architecture is there if not perfect or final, and it’s several steps beyond the corresponding init on macOS.

With this new tech in place, I’m starting to wonder about some older APIs like Cocoa Touch’s drawing stack, which lets you push and pop contexts for immediate drawing. It’s handy for using UIKit calls to draw into custom Core Graphics bitmap contexts. Is that still going to be around and used after WWDC this year? Or next year? Or will it be subsumed into UIGraphicsImageRenderer? It looks ripe for redesign and replacement.

I also don’t think UIGraphicsBegin/EndImageContext is long for the world. It was first introduced in iOS 2. It may be deprecated in iOS 11. The new APIs feel more appropriate to the design and philosophy of iOS, and these calls always stood out as a very odd approach.

But let me get back to the issues of writing “Swift Drawing”. When it comes to book, platform dichotomy hits hard. To get a sense of how much effort it would take to write about drawing for both platforms, I worked on my blend mode appendix sample code this weekend.

This is extremely simple code. It just iterates through  the standard Core Graphics blend modes to create stock samples. The appendix describes each mode We’re talking about maybe a page of code. Getting it to Cocoa? Not so easy.

I put together a very rough skeleton granting Cocoa the basic abilities of Cocoa Touch. I’m not very happy with this code and I’m not sure I’m going to keep pushing on this code or developing its capabilities, which is why it’s in a gist and not a repo.

I suspect we may see new image APIs — both Cocoa and Cocoa Touch — this WWDC. I don’t want to compete with Apple APIs and I also don’t want to have to write two completely distinct drawing books: one for iOS and one for macOS.

So I’m still struggling because while most basic calls for CoreGraphics are interchangeable across platforms, the Cocoa and Cocoa Touch layers are not. If I go with samples that support both platforms, I have to pick one of the following approaches:

  • create an artificial UIKit for Cocoa (that is a disconnect for macOS readers),
  • create an unrealistic platform-independent backbone to unify Cocoa and Cocoa Touch, which means I can’t talk to Cocoa Touch readers in their native language (that is objectively bad), or
  • stick with Cocoa Touch like I did in the original book (simplest but excludes macOS readers).

After this weekend’s experimenting, I’m leaning towards keeping things mostly iOS-centric. I may mix in a bit of “fake UIKit”.

I know I don’t want to go the route of “Color”/”Font”/”BezierPath”/”LayoutConstraint” cross platform types that I use in my own development work. It’s fine to use pseudo-types and typealiases internally but it’s not a way to introduce native tech in a book. Books should teach to the platform with the least distance between the reader and the APIs. No dependencies, few workarounds, minimal obfuscation.

I could build a small set of “fake UIKit” calls for macOS samples. This would allow me to focus discussions on the true cross-platform features like gradients, paths, colors, and bitmaps, without having to write two entire books at once, but I’m not sure it’s worth the effort or the hardship on macOS readers.

The costs look like this:

  • Full macOS support would double my work.
  • Adding compatibility discussions and partial macOS code would add about 60% or more work.
  • A minimal “fake UIKit” and a few references in-book to this approach, I could probably squeak by with about 25-35%.
  • Based on initial feedback, macOS sales would be about 10% at most of my readers.

Bottom line: macOS is a big old monkey wrench for this particular project. After investing a weekend, I’m not sure I want to go there but I’m interested in hearing your feedback after looking at my samples and prototype gists.

Swift Drawing: Would you buy this book?

Over the years, I have received any number of letters, emails, and tweets asking if I were going to update my iOS Drawing book. I first wrote a version for Addison Wesley/Pearson as a kind of fun side project between major iOS releases and it was warmly received. Readers liked the practical solutions for low-level drawing and fancy effects.

Since then iOS evolved and Swift arrived. With new types like UIGraphicsImageRenderer and type extensions for structs like CGRect, drawing has a lot of updated power tools on hand and ready to deploy.  Using C-based APIs with Swift can be a bit tricky, so it might be nice to have some guidance and examples. Plus, playgrounds now make the perfect sample code platform.

So would you be a potential purchaser  if I wrote this? I updated about 25% already, just to get a feel for the changes (and I think they’re quite cool), and am looking at using Leanpub to roll out the book a bit at a time. I’m hoping there’s enough traction out there in potential reader-land to make this worth building. I’d anticipate finishing just before WWDC.

Thoughts? Interest? Please let me know. Thanks!

Dear Erica: Playground Support Folder

“N” asks: “Hey, is the “shared playground folder” long gone, or does it still exist?”

Still there, still useful.

The big difference for long-time playground users is that it moved into the PlaygroundSupport module from the XCPlayground module. The latter was deprecated in Xcode 7. It’s a tiny module that supports playground-specific features. This constant (playgroundSharedDataDirectory) gives you a well-defined sandboxed folder that’s shared between all playgrounds.

This is, by the way, a terrible symbol name (take note!), as it returns a URL. It used to return a string but the name never got updated:

public let playgroundSharedDataDirectory: URL

I often build playground-specific subfolders so my directory doesn’t get all messy.

Another valuable feature is indefinite execution support (needsIndefiniteExecution) for playground pages that have to perform asynchronous work before completion. You can use this support to build little playground-based utilities instead of writing shell scripts.

I have some pages that work with Imgur, Google search, Wolfram queries, etc. A nice thing about building in playgrounds vs shell is that you can integrate audio and visual elements rather than having to save them to files and open them in helper applications.

If you’re writing API utilities, enable manual execution. Constant reloads can almost immediately deplete, for example, your Gist API query count for the day. Oops.

In Xcode, the shared data folder is available for iOS, macOS, and tvOS playgrounds. The shared data folder is not available on iOS’s Swift Playgrounds. This policy discourages custom local storage and access beyond standard media library locations.

There are some further protocols and types under the PlaygroundSupport umbrella in Swift Playgrounds. These aren’t available for Xcode playgrounds because they’re meant for use in Playground Books.

The extra functionality is part of Playground Book support, which underlies the tech in “Learn to Code”, etc. These additional APIs include items like a key-value data store, message passing between the live view and the primary playground page, and more.

If you want to learn more about Playgrounds, I have a book.  It discusses the features you use in Xcode and an overview of how to use iOS Playgrounds. I quite deliberately did not include much about Playground Book authoring as the topics are somewhat orthogonal.

I’ll probably be revising both Playground Secrets and Power Tips and my Swift Documentation Markup after WWDC. There’s also a three-book bundle available with Swift from Two to Three.

Swift Style: Now Available for Amazon Pre-Order

Swift Style is almost wrapped up. I’m just waiting for some final copy edits. Notably, pre-orders are live on Amazon. (You can ignore the dates, page counts, etc there. They’re just place-fillers.) I just did a product video for Amazon, which hopefully will be posted over the next few weeks.

Once printed, Style will be on sale at all the major retailers as well as at Pragmatic. Pragmatic gives you the option of hybrid ebook/printed bundles, and gives me a slightly better slice of the royalty pie, if that matters to you. It’s a nice thing for me.

I’ll be remote talking about the book and Swift Style at PlaygroundsCon on the 24th (the 23rd in the US) this month and Forward Swift 2 on March 2. I also recently gave a talk at Realm’s Swift user SLUG meetup, which you can watch by following the link earlier in this sentence.

That’s not to say this project is done. Swift Style evolved from talking to developers. It represents viewpoints from the larger Swift development community. That process can and will continue as people read the book and I expand its guidance. The people at Pragmatic have been lovely in helping me plan out the book’s future as well as its present.