Topics

#164: Swift Tricks 🐇🎩

Topics

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 their effects. Let's get started.

@autoclosure

This attribute can help save space when writing simple closures:

func cache(key: String, @autoclosure cacheIf: () -> Bool)

Now, the compiler will infer the curly braces {} around our statement:

cache("spaceships", cacheIf: ships.count > 0)

private(set)

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 reads, but writes can only happen in the source file where it's declared.

For frameworks, we can configure both the getter/setter explicitly:

public struct Droid {
  public private(set) var number: String
}

final

When optimizing performance-critical code, 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 all the class's functions and properties.