---
title: "#164: Swift Tricks 🐇🎩"
url: https://littlebitesofcocoa.com/164-swift-tricks
author: Jake Marsh
published: 2016-01-07
topics: ["Swift","Techniques"]
description: "In Bite #159, we started looking at some syntactic shortcuts in Swift. Today we'll continue by looking at a few (perhaps) lesser-known Swift tricks, and..."
---

# #164: Swift Tricks 🐇🎩

By Jake Marsh, January 7, 2016. HTML: https://littlebitesofcocoa.com/164-swift-tricks

In [Bite #159](https://littlebitesofcocoa.com/159), we started looking at some syntactic shortcuts in Swift. Today we'll continue by looking at a few (perhaps) lesser-known Swift tricks, and their effects. Let's get started.

## @autoclosure

This **attribute** can help save space when writing simple **closures**:

``` swift
func cache(key: String, @autoclosure cacheIf: () -> Bool)
```

Now, the compiler will <i>infer</i> the curly braces `{}` around our statement:

``` swift
cache("spaceships", cacheIf: ships.count > 0)
```

## private(set)

``` swift
struct Spaceship { private(set) var name = "Untitled" }
```

With the `private(set)` declaration, we're telling the compiler this **property** has the default access-level of `internal` for <i>reads</i>, but <i>writes</i> can only happen in the source file where it's declared.

For frameworks, we can configure both the getter/setter explicitly:

``` swift
public struct Droid {
  public private(set) var number: String
}
```

## final

When optimizing performance-critical code, [dynamic dispatch](https://en.wikipedia.org/wiki/Dynamic_dispatch) can be our enemy.

If our **class's properties** and **functions** can be overridden by **subclasses**, we're going to pay the performance cost of an indirect call or access every time we use one of those **functions** or **properties**.

We can easily prevent this by declaring a **property** or **function** `final`.

This way, any attempts to override it will result in a compile-time error. We can also declare a **class** `final`, which applies the `final` keyword to <i>all</i> the class's **functions** and **properties**.

<img src='https://media.littlebitesofcocoa.com/bite-assets/164-swift-tricks-final-error.png' style='max-width: 463px;' />
