Archive for April, 2015

Swift: Occam’s Code Razor


I’m continually fascinated by how Swift compiler inferencing enables you to omit code details. When you assign a value to a variable, Swift infers the type on your behalf. The two following lines are therefore effectively identical.

var num : Double = 32.0
var num = 32.0

The floating point literal used in the assignment enables the compiler to infer the Double type in the second example.

Read On…

Swift: Stupid Reflection Tricks #1

Range wars aren’t limited to the old wild west. I was kicking around some code and put together the following, which is admittedly bad on so many levels.

Lily Ballard saw that, sighed, shook his head, and patiently recommended the following instead:

Lily B points out that String.Index is an index of Characters, not UTF-16 code units, and is presumably using some other internal offset. He adds, accessing values with String.Index is a constant-time operation; character offset (or UTF-16 code-unit offset or whatever) is not constant-time so it’s probably using an offset into whatever backing storage the String is currently using.

Swift: Counting emoji groups

Update: Confirmed as bug (“Indeed.  We consider this to be a bug, not a feature, and are tracking it as rdar://20511834″) by Chris Lattner. Thanks to Joseph Lord for the heads up.

Apple’s new emojis are adding both culturally and programmatically exciting developments. Take care because your previous string counting routines (“countElements” and later “count”)  may not take composed character sequences into account. Here’s an example of where you may get tripped up by this technology.

Here’s a single emoji . When you count it, it returns one character.

Screen Shot 2015-04-16 at 9.47.32 AM

Here’s another single emoji. When you count it, it returns two characters. That’s because this is a new-style emoji composition:

Screen Shot 2015-04-16 at 9.48.55 AM

Some emoji now offer grouping and skin-tone variations, like this one does.

Screen Shot 2015-04-16 at 9.40.34 AM

If you iterate through the emoji characters, you see that the newemoji example is composed of two items that are composited together to produce the emoji-of-color.

Screen Shot 2015-04-16 at 9.50.34 AM

You see similar groupings in family-style and couple-style emojis. Here’s a family group. (I’m still trying to figure out where the blue and green shirts come into this.)

Screen Shot 2015-04-16 at 9.52.08 AM

Over at devforums, Andrew Carter posted a solution for handling composed sequences. It involves enumerating substrings using grouped character sequences. Here’s my take on that solution, creating a computed composedCount property for strings.

You end up with a count that treats composed sequences as single entities, returning a count of 1 instead of 4 for the family string shown above.

There are several notes in the standard library module about using composed characters, such as for substringWithRange (“Hint: Use with rangeOfComposedCharacterSequencesForRange: to avoid breaking up composed characters”) and (“Note that the length of the range returned by these methods might be different than the length of the target string, due composed characters and such.”).

Swift: The joys of cascading lets

Today, I wrote a fortune shell script to demonstrate how Swift could be used for scripting without having to build an entire application. I ended up using cascading let statements in a way I haven’t really to date. When 1.2 introduced these to “avoid the pyramid of doom”, I didn’t quite see how well they created a readable stack of steps.

What’s particularly interesting to me is how these steps short-cut the normal call/test for error/respond-to-error Cocoa-y flow of things. If any step fails, everything fails, leading to a central fail point (return nil). Explaining what went wrong isn’t easy to detail any further unless all the calls subscribe to an NSError** pattern.

The if-statement feels a little like an overstuffed turkey, which is not necessarily a good feeling when writing code.  I’m still trying to decide if I love this or not.

Swift: Var parameters


Swift variables use let and var to indicate whether their values are immutable (cannot be changed after the initial assignment) or mutable (can be updated at will). What many newer Swift developers don’t realize is that closure and function parameters can also be annotated by var and let.

Read On…

Swift: Interactive Documentation and the Future of the Playground

Video first so you get the idea of how interactive controls could support playgrounds. You can watch the full-size version here.

Like all things Swift and Playground, this is more a proof of concept than anything practically deployable. You can download this playground and kick its tires from my github repo. If the running version appears dimmed, kick-start it with Editor > Execute Playground.

Read On…

Swift: Working with Unmanaged Objects

In rare cases (which are growing rarer by the day) a Core Foundation function may return a C-pointer or an object reference embedded into an Unmanaged wrapper. You encounter these in the older, dustier, and stranger parts of Cocoa where grues still lurk in shadows. You must transfer Unmanaged references into the normal memory management system before working with them in Swift .

Here’s my current understanding of the situation. Feel free to correct any mistakes and I’ll update this post.

An Unmanaged wrapper, like an Optional wrapper, provides a layer of safety between your code and a potentially nasty crash.  The Unmanaged<T> type stores a pointer whose memory is not controlled by the Swift runtime system. Before using this data, you take responsibility for how this memory should stay alive.

In Cocoa, this works very much like bridging in Objective-C. Unwrap any object with an existing +1 retain count using takeRetainedValue(). This applies to any item built with Create or Copy in its name.

For example, UTTypeCopyPreferredTagWithClass returns a +1 CFString instance. Assign this result with  takeRetainedValue(), making sure to test for failed calls. Unwrapping nil causes nasty crashes that even blessed potions of restore life will not fix. (In Swift, there is no @try, there is only d’oh!) (And potentially d’oh not, if you listen to that Yoda guy.)

public func PreferredFileExtensionForUTI(uti: String) -> String? {
    if let result = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassFilenameExtension) {
        return result.takeRetainedValue() as String
    } else {
        return nil

Use takeUnretainedValue() to unwrap any object built by a Core Foundation function with Get in its name (for example, CFAllocatorGetDefault()) and constants passed as unmanaged objects (for example kLSSharedFileListSessionLoginItems). These items are not automatically retained for you. Unlike takeRetainedValue(), calling takeUnretainedValue() will not consume a retain upon unwrapping.

These functions follow the patterns established in Apple’s Memory Management Programming Guide for Core Foundation, where you can read more about the “Create Rule”, the “Get Rule”, and other details about memory ownership policies.

Update: Cocoa Kevin writes “If you have an Objective-C framework or are developing one that you would like people to use in their Swift application and there are methods or functions in your Objective-C framework that return CoreFoundation objects, you need to decorate your methods or function names with CF_RETURNS_RETAINED or CF_RETURNS_NOT_RETAINED. The CoreFoundation naming rules is not enough according to the Swift compiler. If you don’t decorate your methods or functions then CoreFoundation objects will be returned as unmanaged.”