Archive for the ‘Books’ Category

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.

Overdrive, DRM, and Adobe Digital Editions

The Denver library recently migrated its ebook system. Incidentally, it wiped all my holds in the process and I have no idea what stuff I was waiting to read. So if you recced anything over the past 6 months and it was popular, chances are that I need you to remind me to read it again.

Anyway, today my first hold came in on the new system. I downloaded the ascm file as usual, double clicked, and when Adobe Digital Editions opened, I got this on my screen:

Yikes. I immediately assumed it was time to update Adobe Digital Editions. So I did that. And I tried opening it up again and I got this:

While you can see the massive UI improvements Adobe has made to its signature Mac e-reader, I was still rather stuck.

So I googled for E_ACT_NOT_READY and “IO Error on Network Request” and tried all the things that didn’t work until I found something that did work.

What didn’t work:

  • Clearing out ~/Documents/Digital Editions
  • Creating a new ~/Documents/My Digital Editions
  • Quitting and restarting the apps
  • Rebooting

What did work was reauthorizing my computer. Dunno why. I deauthorized and then reauthorized — good thing I remembered my username and password because it has been a gadzillion years since I did this last — and boom it finally worked.

(If you want to remove authorization by hand, toddle over to ~/Library/Application Support/Adobe/Digital Editions and kill the activation.dat file.)

Anyway, Scott Sigler’s “Alive” is now on my system ready for reading. I have no idea why I put this title on hold and who recommended it to me. I hope it’s good. Here’s finger’s crossed that this is a good read.

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.

Buy a book: Swift Style

esswiftscaled

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!