Xcode Playgrounds book: New edition submitted to iTunes #swiftlang


It may be a little hard to see the words between “second” and “edition” but it now reads like this:

Screen Shot 2015-10-08 at 4.15.03 PM

Given all the updates I had to do this week, it’s more than a “smidge” and probably should have been a third edition.

Once again I want to thank everyone for your continued support of this book. If you haven’t bought a copy yet, you can grab the latest edition from the iTunes Bookstore. The update should go live tomorrow. Check in iBooks for pending updates.

If you’ve already bought, THANK YOU. Without your support, I would not have the flexibility to keep expanding and enhancing this project. So please keep spreading the word: your evangelism means everything to me. Tell your friends, your boss, your colleagues, and your computer-programming pets to pick up a copy.

So what’s new in this edition? I’ve done a back to front update to incorporate all the new XCPlayground features in Xcode 7.1 beta 3: the new liveView feature that can be used with views and view controllers (and the XCPlaygroundLiveViewable protocol that supports rendering arbitrary model objects), the new ways to continue execution and capture values, etc.

I also found at least one stray println (bad me!), a few places where updated code did not get updated screenshots, and so forth. If you find any errors, please drop me an email. I’m always happy to update where I can.

Next up, when I’m not working on reviewing copyedits for the Swift Developer’s Cookbook (now available for pre-order), I think I’ll be working on my short illustrated guide to header docs.

Thanks again, be well, and don’t be a stranger. I’m open to suggestions, feedback, book requests, and kitten gifs.

Dear Erica: What’s iff?

Dear Erica,

I’ve been enjoying your blog for a while now, and I’ve got a Swift question that’s been nagging me and have had no luck with Google, so I was hoping you might be able to help.
What is ‘iff’? At first I thought it was just a typo for ‘if’, but I searched and there’s 184 uses of it in the Swift code documentation. It seems to be used when ‘if’ would be appropriate, but is it really possible it was mis-spelled THAT many times?

Hi Rob,

You see this pop up in the standard library a lot, for example:

/// Return `false` iff `t0` is identical to `t1`; i.e. if they are both
/// `nil` or they both represent the same type.

iff means “If and only if”. Here’s a Wikipedia write-up about this.

In logic and related fields such as mathematics and philosophy, if and only if (shortened iff) is a biconditional logical connective between statements…In that it is biconditional, the connective can be likened to the standard material conditional (“only if”, equal to “if … then”) combined with its reverse (“if”); hence the name. The result is that the truth of either one of the connected statements requires the truth of the other (i.e. either both statements are true, or both are false).


– E

Tracking Swift Identities: #swiftlang

Swift’s deinit support makes it simple to track when instances deallocate. You can throw a print statement in there and watch when things go away.

deinit {
    print("Deallocating instance")

If you’re going to watch object lifecycles, it helps to track which object you’re dealing with. Swift value types don’t really have identifiers. There’s no “notion of identity” for structs, enums, functions, and tuples. For classes, though, you can use ObjectIdentifier to fetch a unique identifier.

class MyClass {
    init () {
        print("Creating instance", 
    deinit {
        print("Deallocating instance", 

Handy for tracking things. Here’s an example that goes through ridiculous loops in order to force an item past its natural life:

struct HandlerStruct {
    let ptr: UnsafeMutablePointer<Void>
    func unsafeFunc() {
        let f = Unmanaged<MyClass>

class MyClass {
    let message = "Got here"
    func test() {
        let ptr = UnsafeMutablePointer<Void>(Unmanaged<MyClass>
        let b = HandlerStruct(ptr: ptr)
        let delayTime = dispatch_time(
            Int64(1 * Double(NSEC_PER_SEC)))
            dispatch_get_main_queue()) {
    init () {
        print("Creating instance",
    deinit {
        print("Deallocating instance", 


If you switch the retained code to unretained, you’ll see the deallocation followed by the crash-and-burn when the now-deallocated instance is accessed by the handler.

Thanks Josh W and Mike Ash

Why Apple TV

Was having a discussion today about what apps are suitable for Apple TV and I thought I’d share some thoughts.

  • Expect lower discoverability. I can’t imagine people will have as much tolerance for browsing on TV as they will on a desktop or phone/tablet.
  • Think living room. Focus on entertainment and information. I don’t think there’s going to be a huge demand for, for example, live earthquake listings or budget calculators versus games and traffic reports.
  • Consider motion. The remote has some accelerometer functionality built in. Think how your apps can engage customers in motion, the way that Wii was designed to get users up off the couch.
  • Design for the limits of the remote but don’t be boring. Frogger apps and sidescrollers take you only so far. Trivia challenges will work a lot better than pictionary ones with these limited input devices.
  • Supplement what people are already doing on Apple TV, which is primarily entertainment delivery. How about an app that makes rental suggestions?
  • Target kids. Being able to engage the family while parents read or prepare dinner is a really big opportunity for this new market.
  • Don’t try to out-siri Siri. Apple’s already building in features to answer questions, perform personal assistant tasks. This is not an area that’s going to be easy to compete in. Ditto for any kind of experiential screensaver stuff. Don’t take Apple on head first. You won’t win.
  • Simplify UIs. If you are going to build for the non-game market, limit the heck out of your interfaces. Avoid text and focus on a few well-chosen buttons.

Would you buy this book if it existed?


Trying to determine if there would be a big enough demand for this to make it worth breaking out to its own mini-book. Say $4.99, lots of illustrations, examples, and best practices building off this post.

How likely are you to purchase a book like this?

If not, what other topic would you be willing to invest in along the same lines as the playground book: lots of updates, self-published? I need a popular enough general topic to make it worth investing time into.

Thanks for the feedback!


New to Beta 2: Swift 2.1 Playground value drops #swiftlang

Color AppScreenSnapz001

New in Beta 2, you can now drag in and drop colors, images, and files. You don’t see this in the screenshot but if you open the value history pane for the text assignment, it shows the text of that file (my shopping list, for the curious).  The text constant is typed as NSURL. Color is UIColor, Pic is UIImage. No question marks for any of them, thankfully.

  • Interestingly enough, you can drag the tokens around the playground. So if you accidentally drop a picture on the color line, just drag it down to the image assignment.
  • You can also option-drag items to copy them.
  • Double-click colors to open a color picker (yay!), images to open the resources folder to select other resources. Double-clicking on URLs doesn’t seem to do anything that I can find.
  • You cannot resize the wee placeholders but you can resize their value history panes just as if you had typed any other value.
  • You cannot generate swatches from UIColor calls (yet), for example UIColor.blueColor() doesn’t swatchize. I’ve found it easiest to just drag in from outside or copy/drag another swatch and then assign with the color wheel.
  • If the wee icon is colored blue, do not type. Click off of it or your next keystroke will replace it. Blue means selection and they can be overwritten. Easily.

Tip for the wise: do not drag a playground into itself. Seriously. Been there. Done that.

Screen Shot 2015-09-23 at 8.30.41 PM

In any case, the files are copied into the resources folder. So:

  • Don’t copy the same file twice by drag/dropping it. Xcode doesn’t like that.
  • Don’t expect edits on the source file to propagate. Once added, refer directly to the resources folder.
  • Colors aren’t copied to resources, they’re just value items.
  • This is pretty much all you can drop right now. For example, you can’t “copy” URLs from Safari. They come over as pure text and need escaping. Expect the drag and drop vocabulary to expand over time, but right now it’s colors, pics, local file NSURLs.
  • As mentioned, don’t drag a playground onto itself.

Other new things

Quite a lot of changes about how Swift reacts to imported enums, unions, NSNumbers, etc. Worth reviewing the release notes if you work with a lot of cross-language code.

The whole “never use a double-quote in a string interpolation” dies in Swift 2.1.

Expressions interpolated in strings may now contain string literals. For example, “My name is \ (attributes[“name”]!)” is now a valid expression. (14050788)

Some performance improvements in the compiler. Items without any dependencies (that is, marked private) won’t trigger recompilation of other files.

Function types are more lenient now. So you can assign, for example, an Any->Int closure to a String->Any variable. I’m still trying to wrap my mind about whether this is a good thing or not.

Conversions between function types are now supported, exhibiting covariance in function result types and contravariance in function parameter types. For example, it is now legal to assign a function of type Any -> Int to a variable of type String -> Any. (19517003)

This next one is the biggest change for me outside of the playgrounds thing. Which is that errors about map closures (_ -> _ sound familiar?) are now “much more usefully diagnosed”. Can’t wait to kick the wheels on this one.

It’s a Cocoa thing: Print and NSView #swiftlang

Once again the question popped up on why is “print” sending jobs to the printer when run on Cocoa? The answer is that print is an instance method on NSView, which queues print jobs.

If the compiler flags your use of print with a warning, specifically “Use of ‘print’ treated as a reference to instance method in class ‘NSView'”, change your code to use Swift.print (not this). This will avoid starting a print job.