Me as an illustration

Hi, I’m Iva.

I build apps for iPhone, iPad and Mac, and work on the Nextcloud desktop client. These are my notes.

February 16, 2024 · 1 min read

Execution Order of Multiple Defer Blocks

I rarely need to use defer blocks and mostly it is for ending signpost intervals. I checked the possible situation of having multiple and in which order they are executed.

I will save you the talk and show you this simple example code instead:

import Foundation

struct MyType {
    func myFunc() {
        defer {
            print("Declared first!")
        }

        defer {
            print("Declared second!")
        }

        print("myFunc!")
    }
}

let myValue = MyType()
myValue.myFunc()

This code will print:

myFunc!
Declared second!
Declared first!

I am happy to see this!

Me as an Emoji

This means, that defer blocks defined first to end signpost intervals are safe to be executed at last.