Potential SwiftUI Bug. Sheets with multiple detents appear to not deinitalise correctly.

As per the title, I've drafted up a bug report but just wanted to sanity check this is not intended behavior before I sent off the report.

Issue: If you present a sheet in SwiftUI using the .sheet(isPresented: ) and have multiple presentation detents on the view such as .presentationDetents([.medium, .large]) the view being presented appears to not correctly deinitialise when the view is dismissed.

I have a short sample view which can easily demonstrate this.

import SwiftUI

struct ContentView: View {
    @State var showSheet = false

    var body: some View {
        Button("Show Sheet") {
            showSheet = true
        }
        .sheet(isPresented: $showSheet) {
            DetailView()
            // With a single detent, the below class prints "this is denit".
                .presentationDetents([.medium])
            // When multiple detents are specified the detail view appears to not deinit properly.
//                .presentationDetents([.medium, .large])
        }
    }
}

struct DetailView: View {
    let deinitPrinter = DeinitPrinter()
    var body: some View {
        Text("foobar")
    }
}

final class DeinitPrinter {
    init() { print("this is init") }
    deinit { print("this is deinit") }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

If you run this code with just the .presentationDetents([.medium]) you get the expected behavior of the console printing:

  1. this is init
  2. this is deinit

every time you open and close the sheet.

However if you comment out .presentationDetents([.medium]) and uncomment out .presentationDetents([.medium, .large]) you only get this every time you open and close the sheet

  1. this is init

Just wondering if this is expected behaviour and if it is, why? If not I can happily press submit on my bug report.

Cheers.

Accepted Reply

In case anyone stumbles across this thread in the future, I received feedback from Apple in my bug report in feedback assistat and am happy to report this bug is no longer an issue in iOS 17.4.1. 🎊

Replies

I’m running into a similar issue with SwiftUI views presented in sheets not properly deinitializing instances of associated properties. Just tested your snippet with Xcode 15 RC and the DeinitPrinter doesn’t execute its deinit regardless of the detents configuration. In fact, it shows the same faulty behavior even without specifying any detents and using a standard full-size sheet. I’m still investigating, but I wanted to ask whether you can confirm this behavior and whether you’ve found a fix or a workaround. Also, have you filed a feedback?

Add a Comment

In case anyone stumbles across this thread in the future, I received feedback from Apple in my bug report in feedback assistat and am happy to report this bug is no longer an issue in iOS 17.4.1. 🎊