Portrait

I2H3

Notes from work as an app developer for iPhones, iPads and Macs.

RSS Icon GitHub Mastodon

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!

a memoji

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