Alexandros Salazar

One-man melting pot. Software developer. Thinker.

Page 2

The Culmination: Part II

That’s right, I said it. Monads. The boogeyman of functional programming; the impenetrable concept; the arcane mathematical chimera that Haskell programmers swear by while the rest of the world rolls their eyes. I even said that it had something to do with the future of Swift—which of course I can’t possibly know since I don’t work for Apple, but which I decided to fear-monger with anyway.

The truth is, if you’ve come with me this far, you’re almost there with monads. There’s not that much more to them than >>=-—it’s the foundational operation. The rest, what I’m going to cover in this post, is for support and guidance—it’s to make them nice and useful and friendly. It’s to make you like them. And to prove that to you, I’m going to start by solving (with Magical Future Swift) the problem of unwrapping multiple optionals.

• • • • •

Birthday Beth has invited three friends to her party...

Continue reading →

The Culmination: Part I

A big part of programming productively is figuring out the right level of abstraction for any given problem. The answer is not unique, though; there are many approaches to solving the same problem: procedural, object-oriented, functional, etc. Some are better supported in some languages than others, and to a degree what we can use depends on the language we choose. For its part, Swift allows us to idiomatically bring functional abstractions into Cocoa development, which is a big boon—as long as we know how to recognize the patterns that call for them.

Among these patterns, there is one that is fundamental. So much so that I have struggled for several weeks over this post, the culmination of my posts on optionals and error-handling, and I’m still unsatisfied with the result. It’s tempting to treat it as a borderline axiom: as something that can’t be explained, merely recognized in action...

Continue reading →

Implicitly Unwrapped Optionals In Depth

In my last post, I took a detailed look at how Swift’s optional chaining works, and (in passing) at the mechanics of the if-let construct. That accounts for about half the story of optionals. The other half is the story of implicitly unwrapped optionals.

To review, implicitly unwrapped optionals allow us to treat them as if they weren’t optionals at all. Looking at our example from last post, if we change things from optionals to implicitly unwrapped optionals, we can write:

public class Demo {
    public let subDemo:SubDemo!
    init(subDemo sDemo:SubDemo = nil) {
        self.subDemo = sDemo

public class SubDemo {
    public let count:Int = 1

let aDemo:Demo! = nil
let bDemo:Demo! = Demo()
let cDemo:Demo! = Demo(subDemo: SubDemo())

let aCount = aDemo.subDemo.count // CRASH
let bCount = bDemo.subDemo.count // CRASH
let cCount = cDemo.subDemo.count // 1

The rule is that...

Continue reading →

Understanding Optional Chaining

Optionals in Swift are an interesting beast. On the one hand, they’re absolutely essential to dealing with Objective-C and C methods, which can return nil and NULL at will. On the other hand, they’re actually a pretty advanced concept that is tough to drop on unsuspecting developers.

As a bridge between the abstract nature of the Optional type and the well-understood nil semantics of Objective-C, Swift provides optional chaining. Users have to know when they’re dealing with optional types, but other than that acknowledgement, they can use them almost like regular types until unwrapping is needed. To make things even easier, optionals that are known to have a value can be declared as implicitly unwrapped and used as if they weren’t optional at all.

The thing is, with those helpful layers of syntactic sugar, it’s difficult to discern what’s really going on. How does ?. work, exactly...

Continue reading →

Clean Regular Expressions In Swift

UPDATE: The initial version of this article recommended using the __conversion function. Embarrassingly, I had missed this post on the dev forums stating it was going to be removed in Swift 1.0. I have updated this article accordingly. Thanks to @frosty for pointing it out.

The Cocoa regular expression API was introduced in iOS 4 and OS X Lion. Until then, there was no Apple-provided way to do regular expressions in a Cocoa or CocoaTouch application. Sadly the API is shackled to the object-oriented nature of Cocoa, making it verbose and overcomplicated. It hasn’t seen much adoption.1

Well, Swift is here and it’s a brand new day. We have prefix, infix, and suffix operators galore, and a few neat tricks up Swift’s sleeve. Projects like ExSwift are making regexes simpler to use, and I’m going to go over a few possible solutions, including ExSwift’s, and I’ll explain which one I like best...

Continue reading →

Optionals? If We Must

As Rob Napier stated, we don’t know Swift. That’s fine—in fact, that’s great: we get to decide now, when the world is young, what we want it to look like. We can and should look at similar languages for ideas, but a lot of best practices are more community preferences than objective truths. And when it comes to optionals, based in part on the long and complex developer forum discussions on how best to use them, my preference is quickly becoming to avoid them.

• • • • •

Optionals are a tool like any other, and every tool has a use. But coming as we do from Objective-C, we are used to passing nil everywhere: nil as a parameter, nil as a starting value, nil as a logical value, etc. With the nice optional syntax Swift gives us, we can basically turn everything into an optional and have very similar behavior. With implicitly unwrapped optionals, things are even easier: we can use them and...

Continue reading →

Type Variance in Swift

When dealing with Objective-C, we don’t give much thought to the meaning of “type”. We typically deal with primitives (integers, pointers, and typedefs thereof) or classes and their subclasses. Swift introduces a much richer type system, and I’m taking a break from looking at strategies for error handling to delve into the details of Swift types.

• • • • •

In Objective-C, we often deal with inheritance: the idea that one class has all the features of another class, its parent, and adds a few of its own, like so:

class Animal {
    func feed() {

class Cat : Animal {
    func meow() {

var aCat = Cat()

We are also used to the idea that a Cat can be passed anywhere an Animal is expected:

func pet(animal:Animal) {
    println("petting \(animal)")


This property is not unique to classes...

Continue reading →

Error Handling in Swift: Might and Magic—Part II

In my previous post, I showed that defining a map method on the Result enum allows chaining of a series of transformations to a result without caring whether the result was a success or a failure until the value was needed for output. I pointed out at the end, though, that there was a problem with certain types of methods. I’ll address that issue here.

• • • • •

A brief recap. The map method allows chaining any single-input-single-output method on a result, like so:

var finalResult =

The outcomes are what we would expect:

  • If someResult is Result.Success(a), finalResult will be Result.Success(f3(f2(f1(a)))).
  • If someResult is Result.Failure(someString), finalResult will also be Result.Failure(someString).

In other words, the failure is propagated. This is awesome, and works great with...

Continue reading →

Error Handling in Swift: Might and Magic

If distance brings perspective, proximity brings understanding. Concepts that were remote and downright strange when I played with them in Haskell or read about them in Scala are blindingly obvious solutions to any number of problems now that I am programming in Swift.

Take error handling. As a concrete example, dividing two numbers, which will fail if the divisor is zero. This is how I would handle this in Objective-C:

NSError *err = nil;
CGFloat result = [NMArithmetic divide:2.5 by:3.0 error:&err];

if (err) {
    NSLog(@"%@", err)
} else {
    [NMArithmetic doSomethingWithResult:result]

By now, this practically seems like the natural way of doing things; I forget the convolutions I’m going through and how little they correspond to what I really want the program to do:

Fetch me something. If it fails, let me know so I can handle it.

I’m passing parameters, dereferencing...

Continue reading →

Immutable Swift

Swift is a new language designed to work on a powerful, mature, established platform—a new soul in a strange world. This causes tension in the design, as well as some concern due to the feeling that the power of Cocoa is inextricably tied to Objective-C’s dynamic nature.

I don’t have a strong opinion on that—my use of Cocoa generally eschews dynamic dispatch, and I like generics and type inference. Therefore I am fascinated by the possibilities Swift opens up: we are now able to try, in an idiomatic way, constructs that would have been strange and out-of-place in Objective-C. I think they’re exciting, and definitely worth exploring.

• • • • •

A truth that all programmers know: state management is why we get paid. Keeping track of state in an environment with multiple, multithreaded inputs and outputs, each prone to error and failure is like dancing ballet on a mined stage: a delicate...

Continue reading →