Swift Tricks

Software

This is a continuation of a previous post discussing language features in Swift. In this post, we’ll look at a few additional examples.

The nil-Coalescing Operator

The syntax of the Swift language places much more emphasis on the concept of nil than Objective-C did. It’s likely that you’ll be seeing lots of ? and ! operators, as well as conditionals that help to deal with this new strictness. The nil-coalescing operator can reduce some of this cruft. In Swift, the operator is ??. Let’s look at an example:

From this example we can see that the ?? operator evaluates the expression on the left and checks if it is nil. If a value exists, the value is returned. If the value is nil, the expression on the right side is returned.

It’s worth noting that Objective-C also has a nil-coalescing operator, with the slightly different ?: syntax. It seems this operator never got the same amount of love due to Objective-C’s more laissez-faire attitude towards nil values.

Where Clause

Swift 1.2 added the very useful where clause, which allows us to append boolean expressions to an if let statement. Let’s look at an example of how this makes conditionals more concise:

Single-Line Blocks

In Swift, a single-line block returns the result of the expression in its one line of code. This is a nice feature because it affords us some syntactic convenience with mapping, reducing and the like.

However, when the return type of the block doesn’t match the value returned from our single line of code, we get a build error. This is confusing when our type is Void. Let’s look at an example:

Void is a special case in this context. The compiler doesn’t consider the types to match here, despite what our intuition says. To fix this, we add a return statement to the block, making it a multi-line block that doesn’t implicitly return a value.

Ignored Arguments

In a twist on one of the tips from the previous post, we’re revisiting the _ operator. We’ve already looked at how this operator is used to remove external parameter names. Now let’s look at how this operator can ignore entire parameters. Here’s an example from a familiar API:

In this example, the application doesn’t use the launch arguments. We can clearly communicate this by using the _ operator to omit the name of that parameter.

Until Next Time

That’s all for now. Stay tuned for more bite-sized Swift examples in the next post.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s