Better Programming

Advice for programmers.

Follow publication

Member-only story

Top 7 Subtle Swift Features

Alex Dremov
Better Programming
Published in
4 min readApr 18, 2022

background image

1. Keyword indirect

It’s used with enums only. As you know, enums are value type and stored on the stack. Therefore, the compiler needs to know how much memory each enum takes.

As only one option is possible at any moment, the enum occupies the memory of the largest case plus some operational information.

// Just a general enum, nothing fancy
enum Foo {
case bizz(String)
case fizz(Int)
}

But what if we make enum dependant on itself?

// Infinite size??
enum Foo {
case bizz(Foo)
case fizz
}

This definition generates a compiler error.

Recursive enum Foo is not marked indirect

The error makes sense: the compiler can’t calculate Foo size as it tends to infinity. Here comes the indirect keyword.

// Oh, fine
enum Foo {
indirect case bizz(Foo)
case fizz
}
  • Simple: it modifies the enum memory structure to solve the recursion problem.
  • Detailed: .bizz(Foo) is no longer stored inline in memory. Actually, with the indirect modifier data is now stored behind a pointer (indirectly).

Problem solved! Also, we can modify the whole enum as indirect

// Every case is indirect now
indirect enum Foo {
case bizz(Foo?)
case fizz(Foo?)
}

2. Attribute @autoclosure

Swift’s @autoclosure attribute enables you to define an argument that automatically gets wrapped in a closure. It’s mostly used to defer the execution of an expression to when it’s actually needed.

Then, calculate can be called like this:

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Responses (1)

Write a response

thanks for this article — I think, you showed some swift techniques that are undervalued.
you might be interested into my article about Khipu, an architecture that uses enum based DSLs foe messaging and Partial Application — another undervalued…