Victor writes: “How do you remove color swatches from the swatch collection.”
Click on the color picker tool (the dropper icon) and drag it to an empty square. Use the dropper to “sample” the square

Victor writes: “How do you remove color swatches from the swatch collection.”
Click on the color picker tool (the dropper icon) and drag it to an empty square. Use the dropper to “sample” the square
From my editor Trina:
Between now and November 15th, you can enter a sweepstakes that is running on InformIT.com — 10 people who enter the sweepstakes will win a digital learning library, but every entry will earn a a one-time 40% off discount code.
And yes, you can use that discount code to purchase my Swift Developer’s Cookbook. Sounds like a good deal — and it won’t cut into my royalties as far as I can tell, so everyone wins. Here’s the direct link to the sweepstakes page.
Here you go:
Swift 2’s try?
operator bridges optionals and error handling by converting thrown errors into nil results. With it, you can use guard statements and conditional binding to focus development solely on success cases.
guard let foo = try? somethingThatMayThrow else { handle error condition without specific details and leave scope}
You lose any returned error information with this approach. The tl;dr version of the rest of this post is this: Discarding error information is kind of sucky. Why not automagically build in context and error printing with alternatives to try? and try!.
A while back, I shared a basic way to emulate try?
without discarding those errors entirely. The following implementation first prints returned errors and then continues to return the result/nil return type that try?
normally gets you:
func attempt<T>(block: () throws -> T) -> Optional<T>{ do { return try block() } catch { print(error); return nil } }
This works great when returned values play some further role but what do you do when you want to use guard statements with failable procedures that don’t return meaningful values, while retaining attempt
‘s error-printing behavior. For example, consider many of NSFileManager’s file creation and deletion utilities.
NSFileManager.defaultManager().removeItemAtURL(someURL)
Your choices are this: wrap in a do-catch
block (wordy), use attempt
with try?
and then try to wrangle the returned nil value, or use try!
and lose all the error information.
There’s of course, another way. In the gist you find at the end of this post, I’ve built attemptFailable
. It wraps throwing statements in minimal printing guard/try system that returns Boolean values. Here’s how that looks in use:
if NSFileManager.defaultManager().fileExistsAtPath(myPath) { guard (attemptFailable{try NSFileManager.defaultManager() .removeItemAtURL(myURL)}) else {abort()} }
Not ideal, obviously, but pretty handy when writing utilities in playgrounds, which I do more and more these days. (Playgrounds are awesome. Buy my book.)
You can enhance try!
in a similar fashion. The doOrDie
function in this gist creates more informative versions for try-and-die than the Swift-supplied option. Like attempt
and attemptFailable
, it captures context and thrown errors and print both before continuing with standard try!
execution termination.
Here’s the code.
The more time I spend in tvOS and on Apple TV, the more I find that it’s an environment better suited for the “big guy” crowd than independent developers. Its app store is hard for anyone who isn’t a preferred partner and the price points Apple’s partners have launched with won’t sustain a much reduced customer base for anyone who isn’t big to begin with.
I see ATV doing best for successful brands and products who want to extend from iOS rather than introduce new tvOS-specific products. In such cases, ATV offers Apple-watch-like extension of functionality instead of a standalone system.
You can advertise the features directly within an app, and offer tvOS support for free or low costs without compromising your bottom line. The real money remains on iOS and tvOS apps add value. This helps skip any issues of app store discovery.
You cannot compete with built-in content like weather, traffic, schedules, reminders, media access, and so forth. And the tvOS SDK doesn’t offer lightweight glances and complications that would be the best way to supplement media consumption.
When it comes to games, ATV is suffering in several ways. First, it doesn’t offer an Apple branded game controller — it’s all third party. The Siri remote kind of sucks when it comes to interactions, although I have created some Wii-like proofs of concepts for using the remote sideways as a steering wheel.
Real gaming needs more than an accelerometer and the Siri remote doesn’t have the buttons or hand-feel that would win. That means purchasing real controllers and building games that properly leverage those controllers. Those are two serious barriers to surmount. (Plus I should note that games must work with just the Siri remote, according to current Apple guidelines and cannot depend on controller purchases.)
Unfortunately, ATV also has a mission issue. It’s a media center that can also play games. It doesn’t have a big game selling point, whether physical movement like Kinect or Wii or “best games available exclusively” like other consoles.
That said, Apple’s sweet spot has always been health (from jogging with your iPod to HealthKit and ResearchKit). It would be great to see Apple introduce some kind of physical interaction features (like a wii fit board, or whatever) that could build on this “Get Moving” brand and get kids up and off the couch for more physical gaming.
Right now, if kids want to vegetate, they can already do that with their iPads and in any room of their house and in a car. The iPad’s touch screen offers a lot more potential than the TV’s “kind-of-point-at-stuff” interaction. I also think most learning titles are still better on the iPad and with touch interfaces. Think Khan Academy type stuff.
The big question for current ATV apps outside of controller-based-games is “can this kind of be a TV channel?” and if the answer is anything other than a clear “yes”, then tvOS is probably not the right platform.
For example, think of a “Home Control” channel, where you tie into security cameras, garage door states, and thermostats. It’s a great way to integrate existing Apple frameworks with tvOS opportunities.
Life coaching products in particular would also benefit from tvOS check-in and review. It’s a natural fit to extending app flow into the living room. While traditional games have received the most press, I see a real target of opportunity here for display on a screen that’s likely quite close to the kitchen (calorie tracking) and your track sneakers (exercise tracking).
Right now tvOS and ATV feel like they haven’t entirely been realized: as if they’re still more hobbies than products. There’s a lot in these new products to like but I think Apple has to think through this push into applications to better define the niche or niches it intends to fill.
There are dozens of reasons to love Swift tuples. Here are five to get you started.
Tuples can initialize a bunch of variables or constants at once. For example, here’s a typical set of variable declarations. This code creates several variables and establishes initial values for each.
var x = "XX" var y = "YY" var z = "ZZ"
When there’s an underlying semantic relationship between these items, consider placing them into a single line with semicolons. Yes, you can turn your nose up at this but a core relationship is emphasized by reordering the declarations into a one-line presentation. Items are declared together because they have some kind of meaning together:
var x = "XX"; var y = "YY"; var z = "ZZ"
There are, of course, drawbacks. This presentation complicates any modifications you may later need to make to this group: whether inserting or removing variables, or changing their initial values. That’s a bad thing so reserve this approach to items where there is a long-standing logical reason to group.
In fact, you only want to join declarations when there’s some really compelling structural reason these items are grouped together, and you never want to do this with unrelated items. For example, this next snippet is an abomination against Cthulhu:
var myVariable = initialValue; var theta = 0.0; let radius = 6; var userName = "Bill"
Avoid this bad example: you are a good person and a good coder, and don’t want Cthulhu to swallow your soul.
Instead, consider a case when there’s a true uniformity of intent. When such exists, you can ditch the semicolons and re-design your declarations to use a tuple, as in the following line of code.
var (w, x, y, z) = ("WW", "XX", "YY", "ZZ")
This line produces the same symbols as the four separate statement snippets you saw previously, but it does so using a simple parsimonious approach. If w
, x
, y
, and z
are related, why shouldn’t their declarations be related too?
Tuple declarations become slightly more complicated when the compiler cannot immediately infer typing. In such cases, add explicit typing. For example, 5.0 and 9.6 normally default to double values. You can force these to CGFloat
like this:
var (px, py) = (5.0, 9.6) as (CGFloat, CGFloat) // or var (px, py): (CGFloat, CGFloat) = (5.0, 9.6)
Even with underlying relationships, avoid complicated declarations that use mixed types. These force you to cognitively match each variable or constant with a type and initial value. This next line is an example of what you don’t want to do:
var (a, b, c) : (Int, Double, CGFloat) = (1, 2, 3)
Don’t force yourself to match a variable from column 1 with a type from column 2 and a value from column 3. It’s bad coding, it’s bad neurocognitive overloading, and Cthulhu doesn’t need that many souls.
Tuples do more than simplify individual declarations. When looking for targets of tuple opportunity, it’s easy to find instances like these:
var gen1 = seq1.generate(); var gen2 = seq2.generate() let item1 = gen1.next(); let item2 = gen2.next()
and transform them into these:
var (gen1, gen2) = (seq1.generate(), seq2.generate()) let (item1, item2) = (gen1.next(), gen2.next())
But in doing so, you’re missing a big opportunity. Use direct tuple declarations in place of separate declaration proxies. Consider this instead:
var generators = (seq1.generate(), seq2.generate()) let items = (generators.0.next(), generators.1.next()) // thanks Steve
Binding related components into a single tuple offers some great programming wins. Here’s a real-world example that benefits from tuple amalgamation. Here’s the original code before conversion.
func longZip<S1: SequenceType, S2: SequenceType> (seq1: S1, _ seq2: S2) -> AnyGenerator<(S1.Generator.Element?, S2.Generator.Element?)> { var (gen1, gen2) = (seq1.generate(), seq2.generate()) return anyGenerator { let (item1, item2) = (gen1.next(), gen2.next()) guard item1 != nil || item2 != nil else {return nil} return (item1, item2) } }
In this example, both the generator and item assignments would benefit from tuplification.
There’s also a nagging syntactic issue to consider before conversion. Tuple field numbering starts at 0, not 1. So items.0 is relates to gen1
, and items.1
to gen2
. This can be ugly if you’re using 1-based numbering. You’ll want to change this when performing your conversion.
Here’s what you get after tuplifying and re-numbering the variables and type parameters:
func longZip<S0: SequenceType, S1: SequenceType> (seq0: S0, _ seq1: S1) -> AnyGenerator<(S0.Generator.Element?, S1.Generator.Element?)> { var generators = (seq0.generate(), seq1.generate()) return anyGenerator { let items = (generators.0.next(), generators.1.next()) guard items.0 != nil || items.1 != nil else {return nil} return items } }
Notice how much nicer the return statement is as well.
Tuples are basically anonymous structs. As you’ve seen, you get numbered field names for free:
let myTuple = (1, "Hello", 5.2)
gives you
(.0 1, .1 "Hello", .2 5.2)
with each field automatically typed and numbered.
Numbers only take you so far. You can manually add field names to declarations for richer semantics, as in the following example. As you see, “intItem” carries more meaning than “.0”
You can also turn this into a typealias, which you can use to pick up field names:
Unfortunately, this type alias is tied to specific types. You cannot create generic typealiases that refer to structure this way:
typealias PairType<T, U> = (first: T, second: U) // won't work.
That’s a pity. A “Pair” is semantically rich but inherently generic. The answer, at this time, is to work around this with Any
. The Any
type fixes the declaration issue even if it’s aesthetically displeasing:
typealias PairTuple = (first: Any, second: Any) let bar: PairTuple = (2, "hello") print(bar.first.dynamicType) // Int.Type print(bar.second.dynamicType) // String.Type
If you insist on using generics, Mike Ash, tongue in cheek, offers the following alternative:
struct Pa<T, U> { typealias ir = (first: T, second: U) } let foo = Pa.ir(2, "Hello") print(foo.first.dynamicType) // Int.Type print(foo.second.dynamicType) // String.Type
Unfortunately, this beautifully named struct does not work with the original mission statement, despite its otherwise sterling qualities:
let gar: Pa = (2, "Hello") // Error!
When it comes to value swaps, you cannot beat the tuple shuffle. Simply construct tuples out of the items whose values you want to reassign, and use tuple-assignment to move those values around. Here’s an example:
(x, y) = (y, x)
You’re not limited to pairs. You can use this approach with as many variables as required:
(x, y, z, w) = (w, x, y, z)
When executed in optimized code, 2-tuple value swaps are as efficient as the built-in swap
function, and n-tuple value swaps are as efficient as tmp=first, first=second, second=third,...,last=tmp
swaps. It’s a simple, beautiful approach.
Bless pattern matching for it is good. Remember this line from the example at the top of the post?
guard items.1 != nil || items.2 != nil else {return nil}
This code tests to see whether both sequences have been exhausted, returning nil from the combined sequences if all items have been used from both incoming generators. Checking multiple items against nil is a pretty common Swift task, and it’s one that really benefits from tuples.
In this example, there’s a far better approach than looking individually at each tuple field. Pattern matching enables you to leverage an if-case
statement to determine whether a tuple contains a .Some
case or not. Here’s what that test looks like:
if case (.None, .None) = items {return nil}
The if-case here “binds” the tuple field items against the tuple in the case. It uses a single equal sign even though there is no actual assignment here. When items is (nil, nil)
, the generator returns nil.
This statement is kind of an odd bird. The condition looks like you could use it as a boolean intermediate for, for example, a ternary condition:
return case (.None, None) = items ? nil : items // nope! won't work
But this is not legal Swift and will not compile. An if-case performs pattern matching binding and exposes any newly bound symbols in its scope clause. This tuple-test uses a byproduct of binding to add early exit but it’s a bit off-label if you get my meaning.
Sebastian Celis writes, “My personal favorite way to use tuples is when a function really wants to return more than one piece of data. I prefer the tuple to being forced to use an inout parameter”
He’s right. There is never a good reason for you to return multiple distinct values with in-out parameters. Use proper error handling if needed and return a tuple instead.
func status() -> (code: Int, text: String) { // RFC 2324 return (418, "I'm a teapot") }
In-out side-effects? Not even once.
So there you have it. Five really cool ways to use tuples, and this write-up doesn’t even begin to touch on the ways you can use tuples in switch statements.
Tuples are one of the big paradigm-shift areas in Swift (along with algebraic data types, pattern matching, value types, protocol oriented programming, functional programming, etc) but tuples tend to get short shrift in terms of people paying proper attention to them.
Hopefully this post will give them a little of the love they deserve and raise your awareness of their awesomeness and possibilities. Remember: Swift isn’t just about re-writing code using new syntax. It’s about embracing new ways of thinking about and architecting your code.
Ever since Apple introduced iBooks to the Mac, it has been an ongoing source of both frustration and utility. It offers an essential way for keeping on top of the Swift language both during beta periods and outside of them.
Every now and then, however, this happens:
You get stuck into a situation of endless “cannot downloads” in the Mac-based iBooks. (Everything seems to work right on iOS.) And it’s just a pain in the neck.
At first I thought it was the iTunes Connect system, with content status updates. So I contacted iTC and they responded with this helpful email:
I then contacted iTunes Store Customer Support and they responded with this helpful email:
And that was about, oh say, a week or so ago. Nothing since then.
So I set out to search. I found any number of complaints about the problem, a few “solutions” but none of them worked for me. In the end, I had to merge together a few approaches to get iBooks to reset for me.
Now, here’s the bad part. I’m going by memory. I didn’t take good notes because I just wanted the damned thing to work. So going from my imperfect memory, here’s more or less the steps I took. You may have to try re-ordering these because I’m not sure which sequence finally finally took after hours and hours of this stuff.
ps -ax | grep -i BKAgentService
, and kill -9
the process it finds.com.apple.BKAgentService
. You might note that the so call “books that cannot download” actually appear in Data/Documents/iBooks/Books in some form. Deleting them here is pointless. (iBooks has a strange form of memory that will keep accessing the current state even after you delete this container, which is the biggest pain.)When you log back in hopefully, you’ll be able to re-enter your credentials and not get the error that says “Library not found”. If you get that error, you’re usually farked. You can try to recreate the library, quit iBooks, and relaunch, but you’re usually back at the original state of “oh crap, it’s not working”.
Please if you’re fixing things, keep notes because this was clearly not a one-time thing, and let me know the sequence that worked for you.