Adding Swift WatchKit Apps to ObjC Projects is Easy

Great time to be an iOS dev, eh?

Many of us are adding Apple Watch siblings to our apps, most of which will have been written in Objective C, and are likely to stay that way, at least for the foreseeable future. But this is a perfect opportunity to dip our toes into the Swift pool, since it is perfectly feasible to have a watch App and host App written in different languages (they are, after all, different platforms), and there is no need for bridging headers, @objc directives, or in fact any cross-language support at all. The two apps, the iOS host (aka companion) app, and the WatchKit extension (whether it runs on the phone in watchOS 1 or on the watch in wOS 2) communicate by sending each other dictionaries (and/or raw data if you need that), and thus are language-agnostic.

Adding a WatchKit app written in Swift to a pre-existing Objectice C project is delightfully easy, once you are aware of one or two stumbling blocks.

(The differences between Xcode 6 and 7 are, at the time of writing, minimal, but we are dealing here with a wOS 1 watch app, wOS 2 may differ).

Select your project in the navigator:

From The Editor menu select Add Target…

From the iOS group, select  Apple Watch > WatchKit App

Select your phone app’s target:

Choose the Capabilities tab and enable App Groups. Xcode will require you to create a group and give it a name, but will do the rest of the entitlements admin work for you.

Screen Shot 2015-07-18 at 09.58.11

Select the WatchKit Extension target:

In the Capabilites tab, enable App Groups and select the group you created just now.

Select your phone app target again:

In the Build Settings tab, set Embedded Content Contains Swift Code to Yes

Screen Shot 2015-07-18 at 09.54.15

Check your Deployment Targets:

Your existing app may support earlier versions of iOS, and this is not a problem. Set your project’s – not one of the targets’ – Deployment Target (on the Info tab) to 8.2 or higher, since Watchkit will require that.

Screen Shot 2015-07-18 at 11.32.58

Then set your existing phone app’s Deployment Target (General tab) back to whichever minimum iOS you are supporting.

Screen Shot 2015-07-18 at 11.33.37

Version numbers:

Your existing app is unlikely to be at v 1.0 build 1, but your WatchKit Extension and Watch Apps will be, so youll need to change the Info.plist entries to match the phone app, changing these fields:

  • Bundle versions string, short
  • Bundle version

If you have, as we do, several build configurations that set different app ID’s and such, you’ll need to set those up, according to your situation.

And, as people in my office keep exclaiming, boom. You’re ready to go.

Comments section is at your disposal for any errors and updates (wOS 2 is here!).

Adding Swift WatchKit Apps to ObjC Projects is Easy

Partial Functions -> More Happiness

Lots is being written about the use in Swift of patterns from functional programming, but one of my favourites gets relatively little attention.

There is a way to, in effect, subclass functions. Elegant, lightweight, inline even.

We’ll not repeat here the origin and meaning of currying and partial functions. If you haven’t met them, you don’t need to have done here (though I hope to tickle your interest in them), and if you have, well, you have.

So here is a trivial example. Define a function that takes several arguments and returns one. We use a rather strange syntax allowed by Swift (in this case to define a function that takes three strings as arguments, and returns a single string):

func compositeURL (series: String)(season: String)(episode: String) -> String {
return series + "/" + season + "/" + episode

Now we call it repeatedly, duplicating all but one of the arguments, so that we can play with different episodes.

let URL1 = compositeURL("drwho")(season: "11")(episode: "daleksagain")
let URL2 = compositeURL("drwho")(season: "11")(episode: "moredaleks")
let URL3 = compositeURL("drwho")(season: "11")(episode: "daleksoup")

Perfectly acceptable. Now we can find in which episode the most daleks get zapped, read the boolean doctorRegenerates, and whatever.

But there is a another way. The syntax above may look a bit odd, but it allows us to call the function compositeURL, with fewer than the full compliment of arguments. What gets returned then is a function that takes the missing argument(s) and returns compositeURL’s return type:

let episodeURL = compositeURL("drwho")(season: "11") // missing argument! What now?

What gets returned here is a new function which is a more specialised version of the original. Once again, we call the new function repeatedly with the missing argument (the one that wasn’t duplicated in each call to compositeURL above).

let URL1 = episodeURL(episode: "daleksagain")
let URL2 = episodeURL(episode: "moredaleks")
let URL3 = episodeURL(episode: "daleksoup")

Both ways we get back the string “drwho/11/daleksagain” (etc.). But doesn’t the second way look so much neater?

We could also, if we needed to, declare another sub-function of compositeURL,

let seasonEpisodeURL = compositeURL("drwho")

which we can now call each time with a different season and episode.

Yes, the functionality above would likely be coded using iteration, but the point is, this idiom of starting with a function with a large number of arguments (think POST requests, for example) and progressivley specialising them, is a common technique in functional programming. They’re not called sub-functions, though, but partial functions. And the more you think about them, the sexier thay get.

There are, as we see all over the net, many other ways in which Cupertino has added powerful tools to Swift borrowed from functional programming. If this spurs you on to investigate further, here’s my promise to you: Two days learning (the purely functional language) Haskell will save you two weeks of reading through Apple’s Swift book, asking yourself “Yes, but why?”. And you really can learn a lot of Haskell over a weekend, it’s dead easy.

Partial Functions -> More Happiness

Horses for Courses: The Lowly Tuple

Swift offers us a range of structural options, meaning that we don’t need to create larger and more complex (but also more flexible) entities than is appropriate. Many a tuple will save us the effort of declaring a struct, and many a struct will spare us the overheads of class creation.

Being able to declare a bunch of variables, of different types, with just one line of easily readable code ;

var (a, b, c) = (42, 3.142, "To boldly go...")

or some constants;

let (d, e, f) = (16, 32.0, "64")

is, I find, a huge boost to code readability. Swift hasn’t enabled us to redefine the nature of programming here, but it does allow us to write code that resembles the way we think, to a greater extent, at least, than many other languages, ObjC included.

May tuples become our favourite go-to helpers in the near future? How often do we need to throw a few variable into a quick-to-assemble, lightweight structure, which feels like it should be a one-liner?

var johnSmith = ("John", 34, "London", 1.83)

There you have it. No setup, no drama, not even a pointer to an unnecessarily bloated NSArray, just type it like you think it, and you’re done. Yes, there’s a lot you can’t do with tuples, for which other Swift goodies are suitable, but what you can do is pass them around, extract the individual elements, change them, and generally use them as the small, low-cost but flexible structure that they are intended to be.

Setting and getting the elements by index is okay;

johnSmith.1 = 35  //  John just got older

but better still, adding labels makes life even easier.

var jackJones = (name: "John", age: 34, birthPlace: "London", height: 1.83)
var location = jackJones.birthPlace

Going to use a lot of tuples of the same type? Create a typealias,

typealias namedPoint = (Double, Double, Double, String)
let cubeOrigin: namedPoint = (20.0, 20.0 ,20.0, "Rodney")

and again, add labels where more clarity may be needed:

typealias labelled3DPoint = (x: Double, y: Double, z: Double)
var sphereCenter: labelled3DPoint = (2.0, 4.0, 6.0)
sphereCenter.x = 3.0  //  or whatever

To sum up this tuple enthusiasm, if we don’t need any custom functionality for a small structure, no operator overloading, no subclassing and the rest of the powerful arsenal of OOP, then the tuple is coding’s equivalent of a hot glue gun. Simple, quick, not particularly refined. But safe as houses to throw around. Do I care that it looks like easy?


Horses for Courses: The Lowly Tuple

Dark Arts vs. Getting There Quicker

For me personally, there are two giant reasons to love Swift, and neither of them are speedier execution (we’ll make that call when the beta’s not a beta, eh?).

Reason 1:

Swift code looks a lot like the model I have in my head of what’s going on. Passing a trio of values that I will only need once feels like

(x, y, z) = (1,2,4)

and less like creating a dictionary and populating it, even using literal shortcuts:

NSDictionary *dict = @{ @"x" : @1, @"y" : @2, @"z" : @3 };

Iterating through some code a few times should look like

for i in (0..<3){}

why on earth do I want to be creating an explicit NSRange first?

The list goes on and on, so we’ll leave it there.

I’m finding that a page of swift code follows my thought processes much more closely, that more intense code looks more intense on the page, kind of like reading a musical score tells you a lot about the music without even looking at a single note. And we haven’t even mentioned the tyranny of NSNumber. Goodbye

int i = [perfectlySimpleInteger integerValue];

and good riddance.

Reason 2:

Having less to read makes understanding my own or somebody else’s code easier, and therefore quicker, and therefore cheaper. However deeply we may have mastered the Dark Arts of Obj C, Swift is simply going to be quicker to work with. Watch what happens when managers and architects start noticing the difference between giving five thousand lines of Swift and the same code in Obj C to new team members, outside contractors, or whomever. I am pretty sure we’re going to see the bottom line making its voice heard in the pro/contra debates.

It’s hard to escape the impression that many developers are insulted at the very idea of making the code more succinct and easy to understand (“eeee, looks like Python“). But both racing cars and baby-buggies get from A to B quicker when A and B are closer together.

The rest of this blog is an ode to Swift, a blog that is unashamedly dedicated to the positives of moving from Obj C to Swift, and one that will leave thinking up a million things that were better with Obj C to developers doubtless much better than myself.

Dark Arts vs. Getting There Quicker