When you touch down on a button in a scroll view, you can cancel the tap by scrolling. In SwiftUI, this works correctly when the scroll view is not inside a dismissible sheet.
However, if the scroll view is inside a sheet that can be dismissed with a drag gesture, scrolling does not cancel the button touch, and after scrolling, the button tap is activated.
This happens whether the modal is presented from SwiftUI using the sheet modifier, or wrapped in a UIHostingController and presented from UIKit.
This is a huge usability issue for modals with scrollable content that have buttons inside of them.
Video of behavior: https://youtube.com/shorts/w6eqsmTrYiU
Easily reproducible with this code:
import SwiftUI
struct ContentView: View {
@State private var isPresentingSheet = false
var body: some View {
ScrollView {
LazyVStack {
ForEach(0..<100, id: \.self) { index in
Button {
isPresentingSheet = true
} label: {
Text("Button \(index)")
.padding(.horizontal)
.padding(.vertical, 5)
.frame(maxWidth: .infinity, alignment: .leading)
}
}
}
.padding()
}
.sheet(isPresented: $isPresentingSheet) {
ContentView()
}
}
}
SwiftUI
RSS for tagProvide views, controls, and layout structures for declaring your app's user interface using SwiftUI.
Posts under SwiftUI tag
200 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
Is it just me or does running SwiftUI apps using Xcode 16 give so many warnings and errors in the console that it's impossible to debug everything? Even the simplest gestures such as a long press generate a warning. I'm starting to ignore them, which feels negligent. Any insights/tips?
Here is my code in visionOS 2.3
NavigationSplitView {
List {
}
.navigationTitle("Passwords")
} detail: {
Text("Hello")
.navigationTitle("All")
}
The font size of "Passwords" and "All" are smaller than the ones in Passwords app.
Hi everyone,
I've been testing the requestGeometryUpdate() API in iOS, and I noticed something unexpected: it allows orientation changes even when the device’s orientation lock is enabled.
Test Setup:
Use requestGeometryUpdate() in a SwiftUI sample app to toggle between portrait and landscape (code below).
Manually enable orientation lock in Control Center.
Press a button to request an orientation change in sample app.
Result: The orientation changes even when orientation lock is ON, which seems to override the expected system behavior.
Questions:
Is this intended behavior?
Is there official documentation confirming whether this is expected? I haven’t found anything in Apple’s Human Interface Guidelines (HIG) or UIKit documentation that explicitly states this.
Since this behavior affects a system-wide user setting, could using requestGeometryUpdate() in this way lead to App Store rejection?
Since Apple has historically enforced respecting user settings, I want to clarify whether this approach is compliant.
Would love any official guidance or insights from Apple engineers.
Thanks!
struct ContentView: View {
@State private var isLandscape = false // Track current orientation state
var body: some View {
VStack {
Text("Orientation Test")
.font(.title)
.padding()
Button(action: toggleOrientation) {
Text(isLandscape ? "Switch to Portrait" : "Switch to Landscape")
.bold()
.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(10)
}
}
}
private func toggleOrientation() {
guard let scene = UIApplication.shared.connectedScenes.first as? UIWindowScene else {
print("No valid window scene found")
return
}
// Toggle between portrait and landscape
let newOrientation: UIInterfaceOrientationMask = isLandscape ? .portrait : .landscapeRight
let geometryPreferences = UIWindowScene.GeometryPreferences.iOS(interfaceOrientations: newOrientation)
scene.requestGeometryUpdate(geometryPreferences) { error in
print("Failed to change orientation: \(error.localizedDescription)")
}
self.isLandscape.toggle()
}
}
To add a background to the tab content I implement the following background, nesting another modifier equal within this one.
.background(
.background // ERROR: Ambiguous use of 'background'
.shadow(.drop(
color: .primary.opacity(0.08),
radius: 5, x: 5, y: 5)
)
.shadow(.drop(
color: .primary.opacity(0.08),
radius: 5, x: -5, y: -5)
),
in: .capsule
)
Hi,
I have noticed a major change to a SwiftUI API behavior in iOS18.4beta1 which breaks my app's functionality, and I've started hearing from users running the new beta that the app doesn't correctly work for them anymore.
The problem is with views that contain a List with multiple-selection, and the contextMenu API applied with the ‘primaryAction’ callback that is triggered when the user taps on a row. Previously, if the user tapped on a row, this callback was triggered with the 'selectedItems' showing the tapped item. With iOS18.4beta, the same callback is triggered with ‘selectedItems’ being empty.
I have the code to demonstrate the problem:
struct ListSelectionTestView: View {
@State private var items: [TimedItem] = [
TimedItem(number: 1, timestamp: "2024-11-20 10:00"),
TimedItem(number: 2, timestamp: "2024-11-20 11:00"),
TimedItem(number: 3, timestamp: "2024-11-20 12:00")
]
@State var selectedItems = Set<TimedItem.ID>()
var body: some View {
NavigationStack {
List(selection: $selectedItems) {
ForEach(items) { item in
Text("Item \(item.number) - \(item.timestamp)")
}
}
.contextMenu(forSelectionType: TimedItem.ID.self, menu: {_ in
Button(action: {
print("button called - count = \(selectedItems.count)")
}) {
Label("Add Item", systemImage: "square.and.pencil")
}
}, primaryAction: {_ in
print("primaryAction called - count = \(selectedItems.count)")
})
}
}
}
struct TimedItem: Identifiable {
let id = UUID()
let number: Int
let timestamp: String
}
#Preview {
ListSelectionTestView()
}
Running the same code on iOS18.2, and tapping on a row will print this to the console:
primaryAction called - count = 1
Running the same code on iOS18.4 beta1, and tapping on a row will print this to the console:
primaryAction called - count = 0
So users who were previously selecting an item from the row, and then seeing expected behavior with the selected item, will now suddenly tap on a row and see nothing. My app's functionality relies on the user selecting an item from a list to see another detailed view with the selected item's contents, and it doesn't work anymore.
This is a major regression issue. Please confirm and let me know. I have filed a feedback: FB16593120
Following up on my previous question here: https://developer.apple.com/forums/thread/774262
Having solved the clipping problem, I am now trying to overlay some content in front of the RealityView. However, it looks like any content with transparency does not render in front of the RealityView, while opaque views seem to work; placing content with transparency like glassBackgroundEffect() behind the RealityView in a ZStack causes the entire window to flicker.
Additionally, my SwiftUI attachment placed in front of the stereoscopic image plane are invisible if the user look at it straight at 90 degrees. However, if the user look at it from increasing angles from the sides, the attachment gradually turns visible again.
Are these behaviors expected? What is a recommended approach to overlay content in front of a RealityView? Thanks!
Hi folks,
Unsure if I've implemented some sort of anti-pattern here, but any help or feedback would be great.
I've created a minimal reproducible sample below that lets you filter a list of people and mark individuals as a favourite.
When invoking the search function on a physical device running iOS 18.3.1, it crashes with Swift/ContiguousArrayBuffer.swift:675: Fatal error: Index out of range.
It runs fine on iOS 17 (physical device) and also on the various simulators I've tried (iOS 18.0, iOS 18.2, iOS 18.3.1).
If I remove the toggle binding, the crash doesn't occur (but I also can't update the toggles in the view model).
I'm expecting to be able to filter the list without a crash occurring and retain the ability to have the toggle switches update the view model.
Sample code is below. Thanks for your time 🙏!
import SwiftUI
struct Person {
let name: String
var isFavorite = false
}
@MainActor
class ViewModel: ObservableObject {
private let originalPeople: [Person] = [
.init(name: "Holly"),
.init(name: "Josh"),
.init(name: "Rhonda"),
.init(name: "Ted")
]
@Published var filteredPeople: [Person] = []
@Published var searchText: String = "" {
didSet {
if searchText.isEmpty {
filteredPeople = originalPeople
} else {
filteredPeople = originalPeople.filter { $0.name.lowercased().contains(searchText.lowercased()) }
}
}
}
init() {
self.filteredPeople = originalPeople
}
}
struct ContentView: View {
@ObservedObject var viewModel = ViewModel()
var body: some View {
NavigationStack {
List {
ForEach($viewModel.filteredPeople, id: \.name) { person in
VStack(alignment: .leading) {
Text(person.wrappedValue.name)
Toggle("Favorite", isOn: person.isFavorite)
}
}
}
.navigationTitle("Contacts")
}
.searchable(text: $viewModel.searchText)
}
}
#Preview {
ContentView()
}```
I noticed if I show a sheet from a List row, then remove the row the sheet isn't removed from the screen like it is if using VStack or LazyVStack.
I'd be interested to know the reason why the sheet isn't removed from the screen in the code below. It only occurs with List/Form. VStack/LazyVStack gives the expected result. I was wondering if it is an implementation issue, e.g. since List is backed by UICollectionView maybe the cells can't be the presenter of the sheet for some reason.
Launch on iPhone 16 Pro Simulator iOS 18.2
Tap "Show Button"
Tap "Show Sheet"
What is expected:
The sheet should disappear after 5 seconds. And I don't mean it should dismiss, I just mean removed from the screen. Similarly if the View that showed the sheet was re-added and its show @State was still true, then the sheet would be added back to the screen instantly without presentation animation.
What actually happens:
Sheet remains on screen despite the row that presented the sheet being removed.
Xcode 16.2
iOS Simulator 18.2.
struct ContentView: View {
@State var showButton = false
var body: some View {
Button("\(showButton ? "Hide" : "Show" ) Button") {
showButton = true
Task {
try? await Task.sleep(for: .seconds(5))
self.showButton = false
}
}
//LazyVStack { // does not have this problem
List {
if showButton {
SheetButton()
}
}
}
}
struct SheetButton: View {
@State var sheet = false
@State var counter = 0
var body: some View {
Text(counter, format: .number)
Button("\(sheet ? "Hide" : "Show") Sheet") {
counter += 1
sheet.toggle()
}
.sheet(isPresented: $sheet) {
Text("Wait... This should auto-hide in 5 secs. Does not with List but does with LazyVStack.")
Button("Hide") {
sheet = false
}
.presentationDetents([.fraction(0.3)])
}
// .onDisappear { sheet = false } // workaround
}
}
I can work around the problem with .onDisappear { sheet = false } but I would prefer the behaviour to be consistent across the container controls.
I have a SwiftuI App which includes an App Clip. There is one target for the iOS app and one for the App Clip. All good.
But I want to create a new target for the test flight app so that test users can distinguish it from the App Store app. E.g. Test Flight app has a different icon asset file in the target but is identical in all other aspects.
However, when I try to build the test flight target I see the message:
The com.apple.developer.parent-application-identifiers entitlement (...]') of an App Clip must match the application-identifier entitlement ('...') of its containing parent app.
This implies that I’d have to change the entitlement of the app clip, which would mess up the production version so I clearly don’t want to go that route.
Any ideas how to overcome this conflict?
Any help will be greatly appreciated.
Trying to build a calendar/planner app for public school teachers. Classes are held on multiple dates so there is a need for swiftdata to save multiple dates.
There are lots of tutorials demonstrating a multidatepicker but none of the tutorials or videos save the dates, via swiftdata.
My goal is to save multiple dates.
Step 1 is to initialize mockdata; this is done a class called ToDo.
var dates:Set = []
Step 2 is the view containing a multidatepicker and other essential code
Step 3 is to save multiple dates using swiftdata.
Lots of tutorials, code snippets and help using a single date.
But after almost 2 weeks of researching youtube tutorials, and google searches, I have not found an answer on how to save multiple dates via swiftdata.
Also, I don't know how how to initialize the array of for the mockdata.
Here are some code snippets used but the initialization of the array of DateComponenets doesnt work. And saving multiple dates doesn't work either
@MainActor
@Model
class ToDo {
var dates:Set<DateComponents> = []
init(dates: Set<DateComponents> = []) {
self.dates = dates
}
}
//view
struct DetailView: View {
@State var dates: Set<DateComponents> = []
@Environment(\.modelContext) var modelContext
@State var toDo: ToDo
@State private var dates: Set<DateComponents> = []
MultiDatePicker("Dates", selection: $dates)
.frame(height: 100)
.onAppear() { dates = toDo.dates }
Button("Save") {
//move data from local variables to ToDo object
toDo.dates = dates
//save data
modelContext.insert(toDo)
}
}
}
#Preview {
DetailView(toDo: ToDo())
.modelContainer(for: ToDo.self, inMemory: true)
}
Hello Apple Developer Community,
I’m experiencing an issue with my iOS app, "WaterReminder," where it builds successfully in Xcode 16.2 but crashes immediately upon launch in the iPhone 16 Pro Simulator running iOS 18.3.1. The crash is accompanied by a "Thread 1: signal SIGABRT" error, and the Xcode console logs indicate a dyld error related to XCTest.framework/XCTest not being loaded. I’ve tried several troubleshooting steps, but the issue persists, and I’d appreciate any guidance or insights from the community.
Here are the details:
Environment:
Xcode Version: 16.2
Simulator: iPhone 16 Pro, iOS 18.3.1
App: WaterReminder (written in SwiftUI 6)
Build Configuration: Debug
Issue Description:
The app builds without errors, but when I run it in the iPhone 16 Pro Simulator, it shows a white screen and crashes with a SIGABRT signal. The Xcode debugger highlights the issue in the main function or app delegate, and the console logs show the following error:
dyld[7358]: Library not loaded: @rpath/XCTest.framework/XCTest
Referenced from: <549B4D71-6B6A-314B-86BE-95035926310E> /Users/faytek/Library/Developer/CoreSimulator/Devices/2A51383F-D8EA-4750-AE22-4CDE745164CE/data/Containers/Bundle/Application/56D8B44F-6613-4756-89F0-CB33991F0821/WaterReminder.app/WaterReminder.debug.dylib
Reason: tried: '/Users/faytek/Library/Developer/Xcode/DerivedData/WaterReminder-cahqrulxghamvyclxaozotzrbsiz/Build/Products/Debug-iphonesimulator/XCTest.framework/XCTest' (no such file), '/Users/faytek/Library/Developer/CoreSimulator/Devices/2A51383F-D8EA-4750-AE22-4CDE745164CE/data/Containers/Bundle/Application/56D8B44F-6613-4756-89F0-CB33991F0821/WaterReminder.app/Frameworks/XCTest.framework/XCTest' (no such file), '/Users/faytek/Library/Developer/CoreSimulator/Devices/2A51383F-D8EA-4750-AE22-4CDE745164CE/data/Containers/Bundle/Application/56D8B44F-6613-4756-89F0-CB33991F0821/WaterReminder.app/XCTest.framework/XCTest' (no such file), '/Users/faytek/Library/Developer/CoreSimulator/Devices/2A51383F-D8EA-4750-AE22-4CDE745164CE/data/Containers/Bundle/Application/56D8B44F-6613-4756-89F0-CB33991F0821/WaterReminder.app/Frameworks/XCTest.framework/XCTest' (no such file), '/Users/faytek/Library/Developer/CoreSimulator/Devices/2A51383F-D8EA-4750-AE22-4CDE745164CE/data/Containers/Bundle/Application/56D8B44F-6613-4756-89F0-CB33991F0821/WaterReminder.app/XCTest.framework/XCTest' (no such file), '/Users/faytek/Library/Developer/CoreSimulator/Devices/2A51383F-D8EA-4750-AE22-4CDE745164CE/data/Containers/Bundle/Application/56D8B44F-6613-4756-89F0-CB33991F0821/WaterReminder.app/Frameworks/XCTest.framework/XCTest' (no such file), '/Library/Developer/CoreSimulator/Volumes/iOS_22D8075/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 18.3.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/XCTest.framework/XCTest' (no such file)
What I’ve Tried:
◦ Verified that FBSnapshotTestCase is correctly added to the "Embed Frameworks" build phase.
◦ Confirmed that the Framework Search Paths in build settings point to the correct location.
◦ Ensured that all required frameworks are available in the dependencies folder.
◦ Cleaned the build folder (Shift + Option + Command + K) and rebuilt the project.
◦ Checked the target configuration to ensure XCTest.framework isn’t incorrectly linked to the main app target (it’s only in test targets).
◦ Updated Xcode and the iOS Simulator to the latest versions.
◦ Reset the simulator content and settings.
Despite these steps, the app continues to crash with the same dyld error and SIGABRT signal. I suspect there might be an issue with how XCTest.framework is being referenced or loaded in the simulator, possibly related to using SwiftUI 6, but I’m unsure how to resolve it.
Could anyone provide advice on why XCTest.framework is being referenced in my main app (since it’s not intentionally linked there) or suggest additional troubleshooting steps? I’d also appreciate any known issues or workarounds specific to Xcode 16.2, iOS 18.3.1, and SwiftUI 6.
Thank you in advance for your help!
Best regards,
Faycel
I've been running into an issue using .fileImporter in SwiftUI already for a year. On iPhone simulator, Mac Catalyst and real iPad it works as expected, but when it comes to the test on a real iPhone, the picker just won't let you select files. It's not the permission issue, the sheet won't close at all and the callback isn't called. At the same time, if you use UIKits DocumentPickerViewController, everything starts working as expected, on Mac Catalyst/Simulator/iPad as well as on a real iPhone.
Steps to reproduce:
Create a new Xcode project using SwiftUI.
Paste following code:
import SwiftUI
struct ContentView: View {
@State var sShowing = false
@State var uShowing = false
@State var showAlert = false
@State var alertText = ""
var body: some View {
VStack {
VStack {
Button("Test SWIFTUI") {
sShowing = true
}
}
.fileImporter(isPresented: $sShowing, allowedContentTypes: [.item]) {result in
alertText = String(describing: result)
showAlert = true
}
VStack {
Button("Test UIKIT") {
uShowing = true
}
}
.sheet(isPresented: $uShowing) {
DocumentPicker(contentTypes: [.item]) {url in
alertText = String(describing: url)
showAlert = true
}
}
.padding(.top, 50)
}
.padding()
.alert(isPresented: $showAlert) {
Alert(title: Text("Result"), message: Text(alertText))
}
}
}
DocumentPicker.swift:
import SwiftUI
import UniformTypeIdentifiers
struct DocumentPicker: UIViewControllerRepresentable {
let contentTypes: [UTType]
let onPicked: (URL) -> Void
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeUIViewController(context: Context) -> UIDocumentPickerViewController {
let documentPicker = UIDocumentPickerViewController(forOpeningContentTypes: contentTypes, asCopy: true)
documentPicker.delegate = context.coordinator
documentPicker.modalPresentationStyle = .formSheet
return documentPicker
}
func updateUIViewController(_ uiViewController: UIDocumentPickerViewController, context: Context) {}
class Coordinator: NSObject, UIDocumentPickerDelegate {
var parent: DocumentPicker
init(_ parent: DocumentPicker) {
self.parent = parent
}
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
print("Success!", urls)
guard let url = urls.first else { return }
parent.onPicked(url)
}
func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
print("Picker was cancelled")
}
}
}
Run the project on Mac Catalyst to confirm it working.
Try it out on a real iPhone.
For some reason, I can't attach a video, so I can only show a screenshot
Hello!
How can I set appAccountToken when I'm using the new SwiftUI view SubscriptionStoreView for subscription?
Previously I was able to set it as a purchase option here https://developer.apple.com/documentation/storekit/product/purchase(options:) but I don't see purchase options with SubscriptionStoreView.
Thank you,
sendai
I have a SwiftUI View I've introduced to a UIKit app, using UIHostingController. The UIView instance that contains the SwiftUI view is animated using auto layout constraints. In this code block, when a view controller's viewDidAppear method I'm creating the hosting controller and adding its view as a subview of this view controller's view, in addition to doing the Container View Controller dance.
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let hostingViewController = UIHostingController(rootView: TestView())
hostingViewController.view.translatesAutoresizingMaskIntoConstraints = false
addChild(hostingViewController)
view.addSubview(hostingViewController.view)
let centerXConstraint = hostingViewController.view.centerXAnchor.constraint(equalTo: view.centerXAnchor)
let topConstraint = hostingViewController.view.topAnchor.constraint(equalTo: view.topAnchor)
widthConstraint = hostingViewController.view.widthAnchor.constraint(equalToConstant: 361)
heightConstraint = hostingViewController.view.heightAnchor.constraint(equalToConstant: 342)
NSLayoutConstraint.activate([centerXConstraint, topConstraint, widthConstraint, heightConstraint])
hostingViewController.didMove(toParent: self)
self.hostingViewController = hostingViewController
}
I add a button to the UI which will scale the UIHostingViewController by adjusting its height and width constraints. When it's tapped, this action method runs.
@IBAction func animate(_ sender: Any) {
widthConstraint.constant = 120.3
heightConstraint.constant = 114.0
UIView.animate(withDuration: 0.5) {
self.view.layoutIfNeeded()
}
}
The problem is, the SwiftUI view's contents "jump" at the start of the animation to the final height, then animate into place. I see this both using UIView.animate the UIKit way, or creating a SwiftUI animation and calling `UIView.
What else do I need to add to make this animate smoothly?
Hello togehter,
i do have the following question.
If I have my App run in landscape mode and a sheet view get's called, will it be possible to switch automatically from landscape mode in portrait mode and fix this device orientation?
Once the sheet view get's dismissed or closed, the original view will come back and the device orientation shall switch back to landscape mode.
Thanks you so much for your help!
Hi,
Does the iPad Playgrounds app act completely the same way as a MacBook Playground?
I am developing my app on a 2020 MacBook Air M1 using Swift Playgrounds. However, since the testing is going to be done on an iPad Swift Playgrounds, I was worried if my playground would work, since it relies heavily on the screen size etc.
My app runs completely perfect on MacBook Playrgounds, but doesn't work on the iPad simulator on Xcode.
I want to add a tool bar (setting search )to my app just like the apple file app using pure swiftUI, is it possible, if not, can i using a UIKit to implement it.
struct MainView: View {
var body: some View {
TabView {
Tab("View 1", systemImage: "square.grid.3x2") {
View1()
}
Tab("View 2", systemImage: "square.grid.2x2") {
View2()
}
}
.tabViewStyle(.sidebarAdaptable)
}
We use @Query macro in our App. After we got macOS 15.3 update, our App crashes at @Query line.
SwiftData/Schema.swift:305: Fatal error: KeyPath \Item.<computed 0x0000000100599e54 (Vec3D)>.x points to a field (<computed 0x0000000100599e54 (Vec3D)>) that is unknown to Item and cannot be used.
This problem occurs only when the build configuration is "Release", and only when I use @Query macro with sort: parameter. The App still works fine on macOS 14.7.3.
This issue seems similar to what has already been reported in the forum. It looks like a regression on iOS 18.3.
https://developer.apple.com/forums/thread/773308
Item.swift
import Foundation
import SwiftData
public struct Vec3D {
let x,y,z: Int
}
extension Vec3D: Codable { }
@Model
final class Item {
var timestamp: Date
var vec: Vec3D
init(timestamp: Date) {
self.timestamp = timestamp
self.vec = Vec3D(x: 0, y: 0, z: 0)
}
}
ContentView.Swift
import SwiftUI
import SwiftData
struct ContentView: View {
@Environment(\.modelContext)
private var modelContext
@Query(sort: \Item.vec.x) // Crash
private var items: [Item]
var body: some View {
NavigationSplitView {
List {
ForEach(items) { item in
NavigationLink {
Text("Item at \(item.timestamp, format: Date.FormatStyle(date: .numeric, time: .standard))")
} label: {
Text(item.timestamp, format: Date.FormatStyle(date: .numeric, time: .standard))
}
}
.onDelete(perform: deleteItems)
}
.navigationSplitViewColumnWidth(min: 180, ideal: 200)
.toolbar {
ToolbarItem {
Button(action: addItem) {
Label("Add Item", systemImage: "plus")
}
}
}
} detail: {
Text("Select an item")
}
}
private func addItem() {
withAnimation {
let newItem = Item(timestamp: Date())
modelContext.insert(newItem)
}
}
private func deleteItems(offsets: IndexSet) {
withAnimation {
for index in offsets {
modelContext.delete(items[index])
}
}
}
}
Hi,
A class initialized as the initial value of an @State property is not released until the whole View disappears. Every subsequent instance deinitializes properly.
Am I missing something, or is this a known issue?
struct ContentView: View {
// 1 - init first SimpleClass instance
@State var simpleClass: SimpleClass? = SimpleClass(name: "First")
var body: some View {
VStack {
Text("Hello, world!")
}
.task {
try? await Task.sleep(for: .seconds(2))
// 2 - init second SimpleClass instance and set as new @State
// "First" should deinit
simpleClass = SimpleClass(name: "Second")
// 3 - "Second" deinit just fine
simpleClass = nil
}
}
}
class SimpleClass {
let name: String
init(name: String) {
print("init: \(name)")
self.name = name
}
deinit {
print("deinit: \(name)")
}
}
output:
init: First
init: Second
deinit: Second
Thanks