Post

Replies

Boosts

Views

Activity

Runtime crash from SwiftUI.State and variadic types from Xcode 27 Beta 3
I am seeing a weird crash from Xcode 27 Beta 3 when building a variadic type DynamicProperty that also needs SwiftUI.State. This does not crash from Xcode 26. Here is a repro: import SwiftUI struct Repeater<each Input>: DynamicProperty { @State private var storage = Storage() private var input: (repeat each Input) init(_ input: repeat each Input) { self.input = (repeat each input) } } extension Repeater { final class Storage { } } @main struct CrashDemoApp: App { private var repeater = Repeater(1) var body: some Scene { WindowGroup { EmptyView() } } } Here is the crash: Thread 1 Queue : com.apple.main-thread (serial) #0 0x000000019a93aec0 in swift::TargetMetadata<swift::InProcess>::isCanonicalStaticallySpecializedGenericMetadata () #1 0x000000019a946b38 in performOnMetadataCache<swift::MetadataResponse, swift_checkMetadataState::CheckStateCallbacks> () #2 0x000000019a8c85f0 in swift_checkMetadataState () #3 0x00000001004a2c78 in type metadata completion function for Repeater () #4 0x000000019a94cfe4 in swift::GenericCacheEntry::tryInitialize () #5 0x000000019a94c870 in swift::MetadataCacheEntryBase<swift::GenericCacheEntry, void const*>::doInitialization () #6 0x000000019a94f820 in swift::LockingConcurrentMap<swift::GenericCacheEntry, swift::LockingConcurrentMapStorage<swift::GenericCacheEntry, (unsigned short)14>>::getOrInsert<swift::MetadataCacheKey, swift::MetadataRequest&, swift::TargetTypeContextDescriptor<swift::InProcess> const*&, void const* const*&> () #7 0x000000019a93c714 in _swift_getGenericMetadata () #8 0x00000001004a4190 in __swift_instantiateGenericMetadata () #9 0x00000001004a2a5c in type metadata accessor for Repeater () #10 0x00000001004a5094 in type metadata accessor for Repeater<Pack{Int}> () #11 0x00000001004a4fcc in type metadata completion function for CrashDemoApp () #12 0x000000019a9543bc in swift::MetadataCacheEntryBase<(anonymous namespace)::SingletonMetadataCacheEntry, int>::doInitialization () #13 0x000000019a8d2ae0 in swift_getSingletonMetadata () #14 0x00000001004a479c in type metadata accessor for CrashDemoApp () #15 0x00000001004a473c in static CrashDemoApp.$main() () #16 0x00000001004a4a34 in main () #17 0x0000000186e47e00 in start () Here is a repo to demo: https://github.com/vanvoorden/2026-07-17 Please let me know if you have any ideas about that. Thanks!
Topic: UI Frameworks SubTopic: SwiftUI
3
0
215
1w
SwiftUI.State macro overreleasing object from Xcode 27 Beta 3?
Here is a simple class that implements a timer: import AsyncAlgorithms final class Timer { private var task: Task<Void, Never>? init() { let id = ObjectIdentifier(self) print(id, "init") } deinit { let id = ObjectIdentifier(self) print(id, "deinit") self.task?.cancel() } func start() { if let _ = self.task { return } let id = ObjectIdentifier(self) self.task = Task.immediate { print(id, "start") defer { print(id, "stop") } for await _ in AsyncTimerSequence.repeating(every: .seconds(1.0)) { let now = Date.now print( id, now.formatted( date: .omitted, time: .standard ) ) } } } } And here is a simple SwiftUI app to start a timer: import SwiftUI @main struct StateDemoApp: App { @State private var timer = Timer() init() { self.timer.start() } var body: some Scene { WindowGroup { EmptyView() } } } Launching the app from Xcode 26.6 runs correctly: ObjectIdentifier(0x0000000c0c96c020) init ObjectIdentifier(0x0000000c0c96c020) start ObjectIdentifier(0x0000000c0c96c020) 10:40:19 PM ObjectIdentifier(0x0000000c0c96c020) 10:40:20 PM ObjectIdentifier(0x0000000c0c96c020) 10:40:21 PM ... ... ... Launching the app from Xcode 27 Beta 3 breaks: ObjectIdentifier(0x0000000a22c245a0) init ObjectIdentifier(0x0000000a22c245a0) start ObjectIdentifier(0x0000000a22c245a0) deinit ObjectIdentifier(0x0000000a22a2ca80) init ObjectIdentifier(0x0000000a22c245a0) stop This makes no sense to me. Why did my Task stop? Why was my Timer deallocated? Here is a repro: https://github.com/vanvoorden/2026-07-16 Please let me know if you have any ideas why this happened. Thanks!
Topic: UI Frameworks SubTopic: SwiftUI
5
0
203
1w
API to query for Guest User Mode on VisionOS?
Hi! Is there currently any public API for product engineers to query for Guest User mode?^1 Is there an API product engineers can query at runtime to determine if their app is running as a Guest User on visionOS? I am not able to find any API that directly returns this information. But it does look some APIs can indirectly return this. HealthKit can condition some of its response values on Guest User mode.^2 It is possible that querying through HealthKit might be a workaround. But it would require asking for health data even in Vision Apps that do not really need health data. I would still be looking for something like a direct Guest User API if that was available. Thanks!
1
0
382
May ’26
`SwiftUI.Table` Select and Done buttons breaking navigation on iPadOS?
https://github.com/apple/sample-food-truck Hi! I'm following along with the sample-food-truck application from WWDC 2022. I'm seeing some weird navigation issues when building the app for iPadOS. The Table component displays a Select Button for selecting elements and a Done Button disabling that state. These buttons seem to be breaking something about navigation on iOS 18.4.1. It's a nondeterministic issue… but tapping the buttons seems to lead to some corrupt state where the app transitions out of OrdersView and back to TruckView. This code from FoodTruckModel seems to be making a difference: Task(priority: .background) { var generator = OrderGenerator.SeededRandomGenerator(seed: 5) for _ in 0..<20 { try? await Task.sleep(nanoseconds: .secondsToNanoseconds(.random(in: 3 ... 8, using: &generator))) Task { @MainActor in withAnimation(.spring(response: 0.4, dampingFraction: 1)) { self.orders.append(orderGenerator.generateOrder(number: orders.count + 1, date: .now, generator: &generator)) } } } } Commenting out that code and disabling the new Order values coming in seems to fix the issue. Is there any public documentation for me to learn about the Select and Done buttons? I don't see anywhere for me to learn about how these work and what my ability is to customize their behavior. Any ideas? I can repro from device and simulator.
2
0
196
May ’25
Food-Truck-Sample navigation broken from Live Activity?
https://github.com/apple/sample-food-truck Hi! I'm seeing what looks like some weird navigation issue in the Food Truck app. It's from the Live Activity that should deep link to a specific point in the app. There seems be some state where the app is not linking to the correct component. Here are my repro steps on iPhone: Start live activity from OrderDetailView. Navigate to Sidebar component. Tap the Live Activity. App opens TruckView. The App should be opening the OrderDetailView for the Order that was passed to the Live Activity. This seems to work when the app is not currently on Sidebar. Any ideas? I'm testing this on iPhone OS 18.4.1. Is this an issue inside NavigationSplitView? Is this an issue with how Food Truck handles deeplinking?
0
0
101
May ’25
Food Truck Sample animation issue from Table Component
Hi! I'm seeing some weird animation issues building the Food Truck sample application.^1 I'm running from macOS 15.4 and Xcode 16.3. I'm building the Food Truck application for macOS. I'm not focusing on iOS for now. The FoodTruckModel adds new Order values with an animation: // FoodTruckModel.swift withAnimation(.spring(response: 0.4, dampingFraction: 1)) { self.orders.append(orderGenerator.generateOrder(number: orders.count + 1, date: .now, generator: &generator)) } This then animates the OrdersTable when new Order values are added. Here is a small change to OrdersTable: // OrdersTable.swift - @State private var sortOrder = [KeyPathComparator(\Order.status, order: .reverse)] + @State private var sortOrder = [KeyPathComparator(\Order.creationDate, order: .reverse)] Running the app now inserts new Order values at the top. The problem is I seem to be seeing some weird animation issues here. It seems that as soon as the new Order comes in there is some kind of weird glitch where it appears as if part the animation is coming from the side instead of down from the top: What's then more weird is that if I seem to affect the state of the Table in any way then the next Order comes in with perfect animation. Scrolling the Table fixes the animation. Changing the creationData sort order from reverse to forward and back to reverse fixes the animation. Any ideas? Is there something about how the Food Truck product is built that would cause this to happen? Is this an underlying issue in the SwiftUI infra?
0
0
180
Apr ’25
SwiftUI.Entry macro only creating computed default values instead of stored?
https://gist.github.com/vanvoorden/37ff2b2f9a2a0d0657a3cc5624cc9139 Hi! I'm experimenting with the Entry macro in a SwiftUI app. I'm a little confused about how to stored a defaultValue to prevent extra work from creating this more than once. A "legacy" approach to defining an Environment variable looks something like this: struct StoredValue { var value: String { "Hello, world!" } init() { print("StoredValue.init()") } } extension EnvironmentValues { var storedValue: StoredValue { get { self[StoredValueKey.self] } set { self[StoredValueKey.self] = newValue } } struct StoredValueKey: EnvironmentKey { static let defaultValue = StoredValue() } } The defaultValue is a static stored property. Here is a "modern" approach using the Entry macro: struct ComputedValue { var value: String { "Hello, world!" } init() { print("ComputedValue.init()") } } extension EnvironmentValues { @Entry var computedValue: ComputedValue = ComputedValue() } From the perspective of the product engineer, it looks like I am defining another stored defaultValue property… but this actually expands to a computed property: extension EnvironmentValues { var computedValue: ComputedValue { get { self[__Key_computedValue.self] } set { self[__Key_computedValue.self] = newValue } } private struct __Key_computedValue: SwiftUICore.EnvironmentKey { static var defaultValue: ComputedValue { get { ComputedValue() } } } } If I tried to use both of these Environment properties in a SwiftUI component, it looks like I can confirm the computedValue is computing its defaultValue several times: @main struct EnvironmentDemoApp: App { var body: some Scene { WindowGroup { ContentView() } } } struct ContentView: View { @Environment(\.computedValue) var computedValue @Environment(\.storedValue) var storedValue var body: some View { VStack { Image(systemName: "globe") .imageScale(.large) .foregroundStyle(.tint) Text("Hello, world!") } .padding() } } And then when I run the app: ComputedValue.init() StoredValue.init() ComputedValue.init() ComputedValue.init() ComputedValue.init() ComputedValue.init() ComputedValue.init() ComputedValue.init() ComputedValue.init() Is there any way to use the Entry macro in a way that we store the defaultValue instead of computing it on-demand every time?
1
1
506
Feb ’25
Is MapKit.mapCameraKeyframeAnimator broken on macOS 15.2?
Hi! I'm attempting to run the Quakes Sample App^1 from macOS. I am running breakpoints and confirming the mapCameraKeyframeAnimator is being called: .mapCameraKeyframeAnimator(trigger: selectedId) { initialCamera in let start = initialCamera.centerCoordinate let end = quakes[selectedId]?.location.coordinate ?? start let travelDistance = start.distance(to: end) let duration = max(min(travelDistance / 30, 5), 1) let finalAltitude = travelDistance > 20 ? 3_000_000 : min(initialCamera.distance, 3_000_000) let middleAltitude = finalAltitude * max(min(travelDistance / 5, 1.5), 1) KeyframeTrack(\MapCamera.centerCoordinate) { CubicKeyframe(end, duration: duration) } KeyframeTrack(\MapCamera.distance) { CubicKeyframe(middleAltitude, duration: duration / 2) CubicKeyframe(finalAltitude, duration: duration / 2) } } But I don't actually see any map animations taking place when that selection changes. Running the application from iPhone simulator does show the animations. I am building from Xcode Version 16.2 and macOS 15.2. Are there known issues with this API on macOS?
0
0
339
Dec ’24
SwiftUI.Stepper bug from `onIncrement` and `onDecrement`?
Ok… I'm baffled here… this is very strange. Here is a SwiftUI app: import SwiftUI @main struct StepperDemoApp: App { func onIncrement() { print(#function) } func onDecrement() { print(#function) } var body: some Scene { WindowGroup { Stepper { Text("Stepper") } onIncrement: { self.onIncrement() } onDecrement: { self.onDecrement() } } } } When I run in the app in macOS (Xcode 16.0 (16A242) and macOS 14.6.1 (23G93)), I see some weird behavior from these buttons. My experiment is tapping + + + - - -. Here is what I see printed: onIncrement() onIncrement() onIncrement() onIncrement() onDecrement() What I expected was: onIncrement() onIncrement() onIncrement() onDecrement() onDecrement() onDecrement() Why is an extra onIncrement being called? And why is one onDecrement dropping on the floor? Deploying the app to iPhone Simulator does not repro this behavior (I see the six "correct" logs from iPhone Simulator).
9
0
941
Dec ’24
SwiftData Quakes Sample app decoding errors from null magnitudes
Hi! I believe there might be a small bug in the SwiftData Quakes Sample App.^1 The Quakes app requests a JSON feed from USGS.^2 What seems to be breaking is that apparently earthquake entities from USGS can return with null magnitudes. That is throwing errors from the decoder: struct GeoFeatureCollection: Decodable { let features: [Feature] struct Feature: Decodable { let properties: Properties let geometry: Geometry struct Properties: Decodable { let mag: Double let place: String let time: Date let code: String } struct Geometry: Decodable { let coordinates: [Double] } } } which is expecting mag to not be nil. Here is my workaround: struct GeoFeatureCollection: Decodable { let features: [Feature] struct Feature: Decodable { let properties: Properties let geometry: Geometry struct Properties: Decodable { let mag: Double? let place: String let time: Date let code: String } struct Geometry: Decodable { let coordinates: [Double] } } } And then: extension Quake { /// Creates a new quake instance from a decoded feature. convenience init(from feature: GeoFeatureCollection.Feature) { self.init( code: feature.properties.code, magnitude: feature.properties.mag ?? 0.0, time: feature.properties.time, name: feature.properties.place, longitude: feature.geometry.coordinates[0], latitude: feature.geometry.coordinates[1] ) } }
1
0
894
Dec ’24
How to resolve SwiftUI.DynamicProperty on MainActor compiler warning on 6.0?
Hi! I'm running into a warning from a SwiftUI.DynamicProperty on a 6.0 development build (swift-6.0-DEVELOPMENT-SNAPSHOT-2024-03-26-a). I am attempting to build a type (conforming to DynamicProperty) that should also be MainActor. This type with also need a custom update function. Here is a simple custom wrapper (handwaving over the orthogonal missing pieces) that shows the warning: import SwiftUI @MainActor struct MainProperty: DynamicProperty { // Main actor-isolated instance method 'update()' cannot be used to satisfy nonisolated protocol requirement; this is an error in the Swift 6 language mode @MainActor func update() { } } Is there anything I can do about that warning? Does the warning correctly imply that this will be a legit compiler error when 6.0 ships? I can find (at least) two examples of types adopting DynamicProperty from Apple that are also MainActor: FetchRequest and SectionedFetchRequest. What is confusing is that both FetchRequest^1 and SectionedFetchRequest^2 explicitly declare their update method to be MainActor. Is there anything missing from my Wrapper declaration that can get me what I'm looking for? Any more advice about that? Thanks!
4
1
1.3k
Nov ’24
Help understanding `SwiftUI.App` identity lifecycle and need for `SwiftUI.State`?
Hi! I have a stateful object that should be created in my app entry point and delivered through my component graph: @main @MainActor struct MyApp : App { @State private var myAppState = MyAppState() var body: some Scene { ... } } The MyApp is a struct value type… in a SwiftUI world that seems to imply it could "go away" and be recreated as the system sees appropriate. We see this with view components all the time (hence the State wrapper to help preserve our instance across the lifecycle of our identity)… but I'm wondering if this State wrapper is even necessary with an App entry point. Could this struct ever go away? Would there be any legit reasons that this struct should go away and recreate over one SwiftUI app lifecycle (other than terminating the app and starting a whole new process of course)? And what lifecycle is the SwiftUI.State tied to in this example? In a view component our SwiftUI.State is tied to our component identity. In this example… we are tied to app component identity? Is there ever going to be multiple legit app component identities live in the same process? I'm thinking I could just go ahead and keep using State as a best practice… but is this just overkill or is there a real best practice lurking under here? Any more ideas about that? Thanks!
2
0
576
Sep ’24
Unhandled exception finding default Directory URL '+[NSPersistentContainer defaultDirectoryURL] Could not conjure up a useful location for writing persistent stores.'
https://github.com/ordo-one/package-benchmark/issues/264 Hi! I am seeing this error specifically when I try to run the Ordo One benchmarks package with a SwiftData context. I am not sure if there is something missing in Ordo One or if this is some kind of legit SwiftData error. My benchmarks seem to be running fine even after the error prints. Any idea where that error might be coming from (and why I am not seeing that error when running SwiftData from other package executables)?
4
0
727
Aug ’24
ModelContext autosaveEnabled leading to crashes when SwiftUI App moves to background?
Hi! I'm investigating some crashes that seem to be related to ModelContext.autosaveEnabled^1. I don't have a very clean repro test case at this time… but I seem to be seeing crashes when a SwiftUI app moves to the background. I am testing an app built for macOS 14.6.1. I am building from Xcode_16_beta_5. My app is not using a mainContext. My app is building a ModelActor that is running on a background thread (off main). The modelContext inside my ModelActor is set with autosaveEnabled equal to true. The mutations on my state are not being explicitly saved (I am waiting for the system to save automatically). My guess (so far) is that transitioning into the background from SwiftUI is kicking off some kind of logic that is specifically being tied to the main thread… but this is causing problems when my modelContext is created from a background thread. My understanding was that ModelActor could help to defend against threading problems… but this might be a different problem that I did not expect. I am unblocked for now by turning off autosaveEnabled (and manually saving from my ModelActor). That fixes the crashes. Any more thoughts or insight about what could be causing these crashes when my app transitions into the background? Thanks! Thread 1 Queue : com.apple.main-thread (serial) #0 0x000000023108beb8 in ___lldb_unnamed_symbol2827 () #1 0x000000023108ef30 in ___lldb_unnamed_symbol2847 () #2 0x000000023108eca8 in ___lldb_unnamed_symbol2845 () #3 0x000000019bac6144 in __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ () #4 0x000000019bb5a3d8 in ___CFXRegistrationPost_block_invoke () #5 0x000000019bb5a320 in _CFXRegistrationPost () #6 0x000000019ba94678 in _CFXNotificationPost () #7 0x000000019cbb12c4 in -[NSNotificationCenter postNotificationName:object:userInfo:] () #8 0x000000019f489408 in -[NSApplication _handleDeactivateEvent:] () #9 0x000000019fb24380 in -[NSApplication(NSEventRouting) sendEvent:] () #10 0x000000019f771d9c in -[NSApplication _handleEvent:] () #11 0x000000019f322020 in -[NSApplication run] () #12 0x000000019f2f9240 in NSApplicationMain () #13 0x00000001c74c73b8 in ___lldb_unnamed_symbol83060 () #14 0x00000001c7c30ddc in ___lldb_unnamed_symbol132917 () #15 0x00000001c802be0c in static SwiftUI.App.main() -> () () Thread 5 Queue : NSManagedObjectContext 0x6000009c38e0 (serial) #0 0x000000019ba66f94 in constructBuffers () #1 0x000000019ba65e30 in _CFURLCreateWithURLString () #2 0x000000019bad6e7c in _CFURLComponentsCopyURLRelativeToURL () #3 0x000000019cbde864 in -[__NSConcreteURLComponents URL] () #4 0x000000019d3782f8 in -[NSURL(NSURL) initWithString:relativeToURL:encodingInvalidCharacters:] () #5 0x000000019cbdd4d4 in +[NSURL(NSURL) URLWithString:relativeToURL:] () #6 0x00000001a23feef0 in -[NSTemporaryObjectID URIRepresentation] () #7 0x00000002310e0878 in ___lldb_unnamed_symbol4176 () #8 0x00000002310ef480 in ___lldb_unnamed_symbol4401 () #9 0x00000002310eb6e0 in ___lldb_unnamed_symbol4385 () #10 0x00000002310a22b4 in ___lldb_unnamed_symbol3130 () #11 0x00000002310ed4e8 in ___lldb_unnamed_symbol4390 () #12 0x00000002310883dc in ___lldb_unnamed_symbol2799 () #13 0x0000000231087edc in ___lldb_unnamed_symbol2798 () #14 0x000000023109fd24 in ___lldb_unnamed_symbol3021 () #15 0x0000000231086acc in ___lldb_unnamed_symbol2784 () #16 0x00000001a2392144 in developerSubmittedBlockToNSManagedObjectContextPerform () #17 0x00000001a2392004 in -[NSManagedObjectContext performBlockAndWait:] () #18 0x00000002310879ac in ___lldb_unnamed_symbol2797 ()
1
0
651
Aug ’24
SwiftData Model with `updated` variable leads to wrong value being persisted.
Hi! I am seeing some unexpected behavior when attempting to create a Model instance with a variable named updated. I start with a simple Model: @Model final public class Item { var timestamp: Int var updated: Int public init(timestamp: Int = 1, updated: Int = 1) { self.timestamp = timestamp self.updated = updated } } I then attempt to create an item instance: func main() throws { let schema = Schema([Item.self]) let configuration = ModelConfiguration(isStoredInMemoryOnly: true) let container = try ModelContainer( for: schema, configurations: configuration ) let modelContext = ModelContext(container) let item = Item() print(item.timestamp) print(item.updated) } try main() The value of item.timestamp is printing as 1 and the value of item.updated is printing as 0. I have no idea what could be causing that to happen… why would both those values not be printing as 1? Is there some private API that is somehow colliding with the (public) updated variable and causing the item instance to report back with a value of 0? Is there documentation warning engineers that a variable named updated is off-limits and results in undefined behavior? I can fix that by renaming the variable: @Model final public class Item { var timestamp: Int var updatedTimestamp: Int public init() { self.timestamp = 1 self.updatedTimestamp = 1 } } I am unblocked on this (because renaming the variable seems to work fine)… but is there any insight on why this might be happening in the first place? I am building from Xcode_16_beta_5. Thanks!
2
2
518
Aug ’24
Runtime crash from SwiftUI.State and variadic types from Xcode 27 Beta 3
I am seeing a weird crash from Xcode 27 Beta 3 when building a variadic type DynamicProperty that also needs SwiftUI.State. This does not crash from Xcode 26. Here is a repro: import SwiftUI struct Repeater<each Input>: DynamicProperty { @State private var storage = Storage() private var input: (repeat each Input) init(_ input: repeat each Input) { self.input = (repeat each input) } } extension Repeater { final class Storage { } } @main struct CrashDemoApp: App { private var repeater = Repeater(1) var body: some Scene { WindowGroup { EmptyView() } } } Here is the crash: Thread 1 Queue : com.apple.main-thread (serial) #0 0x000000019a93aec0 in swift::TargetMetadata<swift::InProcess>::isCanonicalStaticallySpecializedGenericMetadata () #1 0x000000019a946b38 in performOnMetadataCache<swift::MetadataResponse, swift_checkMetadataState::CheckStateCallbacks> () #2 0x000000019a8c85f0 in swift_checkMetadataState () #3 0x00000001004a2c78 in type metadata completion function for Repeater () #4 0x000000019a94cfe4 in swift::GenericCacheEntry::tryInitialize () #5 0x000000019a94c870 in swift::MetadataCacheEntryBase<swift::GenericCacheEntry, void const*>::doInitialization () #6 0x000000019a94f820 in swift::LockingConcurrentMap<swift::GenericCacheEntry, swift::LockingConcurrentMapStorage<swift::GenericCacheEntry, (unsigned short)14>>::getOrInsert<swift::MetadataCacheKey, swift::MetadataRequest&, swift::TargetTypeContextDescriptor<swift::InProcess> const*&, void const* const*&> () #7 0x000000019a93c714 in _swift_getGenericMetadata () #8 0x00000001004a4190 in __swift_instantiateGenericMetadata () #9 0x00000001004a2a5c in type metadata accessor for Repeater () #10 0x00000001004a5094 in type metadata accessor for Repeater<Pack{Int}> () #11 0x00000001004a4fcc in type metadata completion function for CrashDemoApp () #12 0x000000019a9543bc in swift::MetadataCacheEntryBase<(anonymous namespace)::SingletonMetadataCacheEntry, int>::doInitialization () #13 0x000000019a8d2ae0 in swift_getSingletonMetadata () #14 0x00000001004a479c in type metadata accessor for CrashDemoApp () #15 0x00000001004a473c in static CrashDemoApp.$main() () #16 0x00000001004a4a34 in main () #17 0x0000000186e47e00 in start () Here is a repo to demo: https://github.com/vanvoorden/2026-07-17 Please let me know if you have any ideas about that. Thanks!
Topic: UI Frameworks SubTopic: SwiftUI
Replies
3
Boosts
0
Views
215
Activity
1w
SwiftUI.State macro overreleasing object from Xcode 27 Beta 3?
Here is a simple class that implements a timer: import AsyncAlgorithms final class Timer { private var task: Task<Void, Never>? init() { let id = ObjectIdentifier(self) print(id, "init") } deinit { let id = ObjectIdentifier(self) print(id, "deinit") self.task?.cancel() } func start() { if let _ = self.task { return } let id = ObjectIdentifier(self) self.task = Task.immediate { print(id, "start") defer { print(id, "stop") } for await _ in AsyncTimerSequence.repeating(every: .seconds(1.0)) { let now = Date.now print( id, now.formatted( date: .omitted, time: .standard ) ) } } } } And here is a simple SwiftUI app to start a timer: import SwiftUI @main struct StateDemoApp: App { @State private var timer = Timer() init() { self.timer.start() } var body: some Scene { WindowGroup { EmptyView() } } } Launching the app from Xcode 26.6 runs correctly: ObjectIdentifier(0x0000000c0c96c020) init ObjectIdentifier(0x0000000c0c96c020) start ObjectIdentifier(0x0000000c0c96c020) 10:40:19 PM ObjectIdentifier(0x0000000c0c96c020) 10:40:20 PM ObjectIdentifier(0x0000000c0c96c020) 10:40:21 PM ... ... ... Launching the app from Xcode 27 Beta 3 breaks: ObjectIdentifier(0x0000000a22c245a0) init ObjectIdentifier(0x0000000a22c245a0) start ObjectIdentifier(0x0000000a22c245a0) deinit ObjectIdentifier(0x0000000a22a2ca80) init ObjectIdentifier(0x0000000a22c245a0) stop This makes no sense to me. Why did my Task stop? Why was my Timer deallocated? Here is a repro: https://github.com/vanvoorden/2026-07-16 Please let me know if you have any ideas why this happened. Thanks!
Topic: UI Frameworks SubTopic: SwiftUI
Replies
5
Boosts
0
Views
203
Activity
1w
API to query for Guest User Mode on VisionOS?
Hi! Is there currently any public API for product engineers to query for Guest User mode?^1 Is there an API product engineers can query at runtime to determine if their app is running as a Guest User on visionOS? I am not able to find any API that directly returns this information. But it does look some APIs can indirectly return this. HealthKit can condition some of its response values on Guest User mode.^2 It is possible that querying through HealthKit might be a workaround. But it would require asking for health data even in Vision Apps that do not really need health data. I would still be looking for something like a direct Guest User API if that was available. Thanks!
Replies
1
Boosts
0
Views
382
Activity
May ’26
`SwiftUI.Table` Select and Done buttons breaking navigation on iPadOS?
https://github.com/apple/sample-food-truck Hi! I'm following along with the sample-food-truck application from WWDC 2022. I'm seeing some weird navigation issues when building the app for iPadOS. The Table component displays a Select Button for selecting elements and a Done Button disabling that state. These buttons seem to be breaking something about navigation on iOS 18.4.1. It's a nondeterministic issue… but tapping the buttons seems to lead to some corrupt state where the app transitions out of OrdersView and back to TruckView. This code from FoodTruckModel seems to be making a difference: Task(priority: .background) { var generator = OrderGenerator.SeededRandomGenerator(seed: 5) for _ in 0..<20 { try? await Task.sleep(nanoseconds: .secondsToNanoseconds(.random(in: 3 ... 8, using: &generator))) Task { @MainActor in withAnimation(.spring(response: 0.4, dampingFraction: 1)) { self.orders.append(orderGenerator.generateOrder(number: orders.count + 1, date: .now, generator: &generator)) } } } } Commenting out that code and disabling the new Order values coming in seems to fix the issue. Is there any public documentation for me to learn about the Select and Done buttons? I don't see anywhere for me to learn about how these work and what my ability is to customize their behavior. Any ideas? I can repro from device and simulator.
Replies
2
Boosts
0
Views
196
Activity
May ’25
Food-Truck-Sample navigation broken from Live Activity?
https://github.com/apple/sample-food-truck Hi! I'm seeing what looks like some weird navigation issue in the Food Truck app. It's from the Live Activity that should deep link to a specific point in the app. There seems be some state where the app is not linking to the correct component. Here are my repro steps on iPhone: Start live activity from OrderDetailView. Navigate to Sidebar component. Tap the Live Activity. App opens TruckView. The App should be opening the OrderDetailView for the Order that was passed to the Live Activity. This seems to work when the app is not currently on Sidebar. Any ideas? I'm testing this on iPhone OS 18.4.1. Is this an issue inside NavigationSplitView? Is this an issue with how Food Truck handles deeplinking?
Replies
0
Boosts
0
Views
101
Activity
May ’25
Food Truck Sample animation issue from Table Component
Hi! I'm seeing some weird animation issues building the Food Truck sample application.^1 I'm running from macOS 15.4 and Xcode 16.3. I'm building the Food Truck application for macOS. I'm not focusing on iOS for now. The FoodTruckModel adds new Order values with an animation: // FoodTruckModel.swift withAnimation(.spring(response: 0.4, dampingFraction: 1)) { self.orders.append(orderGenerator.generateOrder(number: orders.count + 1, date: .now, generator: &generator)) } This then animates the OrdersTable when new Order values are added. Here is a small change to OrdersTable: // OrdersTable.swift - @State private var sortOrder = [KeyPathComparator(\Order.status, order: .reverse)] + @State private var sortOrder = [KeyPathComparator(\Order.creationDate, order: .reverse)] Running the app now inserts new Order values at the top. The problem is I seem to be seeing some weird animation issues here. It seems that as soon as the new Order comes in there is some kind of weird glitch where it appears as if part the animation is coming from the side instead of down from the top: What's then more weird is that if I seem to affect the state of the Table in any way then the next Order comes in with perfect animation. Scrolling the Table fixes the animation. Changing the creationData sort order from reverse to forward and back to reverse fixes the animation. Any ideas? Is there something about how the Food Truck product is built that would cause this to happen? Is this an underlying issue in the SwiftUI infra?
Replies
0
Boosts
0
Views
180
Activity
Apr ’25
SwiftUI.Entry macro only creating computed default values instead of stored?
https://gist.github.com/vanvoorden/37ff2b2f9a2a0d0657a3cc5624cc9139 Hi! I'm experimenting with the Entry macro in a SwiftUI app. I'm a little confused about how to stored a defaultValue to prevent extra work from creating this more than once. A "legacy" approach to defining an Environment variable looks something like this: struct StoredValue { var value: String { "Hello, world!" } init() { print("StoredValue.init()") } } extension EnvironmentValues { var storedValue: StoredValue { get { self[StoredValueKey.self] } set { self[StoredValueKey.self] = newValue } } struct StoredValueKey: EnvironmentKey { static let defaultValue = StoredValue() } } The defaultValue is a static stored property. Here is a "modern" approach using the Entry macro: struct ComputedValue { var value: String { "Hello, world!" } init() { print("ComputedValue.init()") } } extension EnvironmentValues { @Entry var computedValue: ComputedValue = ComputedValue() } From the perspective of the product engineer, it looks like I am defining another stored defaultValue property… but this actually expands to a computed property: extension EnvironmentValues { var computedValue: ComputedValue { get { self[__Key_computedValue.self] } set { self[__Key_computedValue.self] = newValue } } private struct __Key_computedValue: SwiftUICore.EnvironmentKey { static var defaultValue: ComputedValue { get { ComputedValue() } } } } If I tried to use both of these Environment properties in a SwiftUI component, it looks like I can confirm the computedValue is computing its defaultValue several times: @main struct EnvironmentDemoApp: App { var body: some Scene { WindowGroup { ContentView() } } } struct ContentView: View { @Environment(\.computedValue) var computedValue @Environment(\.storedValue) var storedValue var body: some View { VStack { Image(systemName: "globe") .imageScale(.large) .foregroundStyle(.tint) Text("Hello, world!") } .padding() } } And then when I run the app: ComputedValue.init() StoredValue.init() ComputedValue.init() ComputedValue.init() ComputedValue.init() ComputedValue.init() ComputedValue.init() ComputedValue.init() ComputedValue.init() Is there any way to use the Entry macro in a way that we store the defaultValue instead of computing it on-demand every time?
Replies
1
Boosts
1
Views
506
Activity
Feb ’25
Is MapKit.mapCameraKeyframeAnimator broken on macOS 15.2?
Hi! I'm attempting to run the Quakes Sample App^1 from macOS. I am running breakpoints and confirming the mapCameraKeyframeAnimator is being called: .mapCameraKeyframeAnimator(trigger: selectedId) { initialCamera in let start = initialCamera.centerCoordinate let end = quakes[selectedId]?.location.coordinate ?? start let travelDistance = start.distance(to: end) let duration = max(min(travelDistance / 30, 5), 1) let finalAltitude = travelDistance > 20 ? 3_000_000 : min(initialCamera.distance, 3_000_000) let middleAltitude = finalAltitude * max(min(travelDistance / 5, 1.5), 1) KeyframeTrack(\MapCamera.centerCoordinate) { CubicKeyframe(end, duration: duration) } KeyframeTrack(\MapCamera.distance) { CubicKeyframe(middleAltitude, duration: duration / 2) CubicKeyframe(finalAltitude, duration: duration / 2) } } But I don't actually see any map animations taking place when that selection changes. Running the application from iPhone simulator does show the animations. I am building from Xcode Version 16.2 and macOS 15.2. Are there known issues with this API on macOS?
Replies
0
Boosts
0
Views
339
Activity
Dec ’24
SwiftUI.Stepper bug from `onIncrement` and `onDecrement`?
Ok… I'm baffled here… this is very strange. Here is a SwiftUI app: import SwiftUI @main struct StepperDemoApp: App { func onIncrement() { print(#function) } func onDecrement() { print(#function) } var body: some Scene { WindowGroup { Stepper { Text("Stepper") } onIncrement: { self.onIncrement() } onDecrement: { self.onDecrement() } } } } When I run in the app in macOS (Xcode 16.0 (16A242) and macOS 14.6.1 (23G93)), I see some weird behavior from these buttons. My experiment is tapping + + + - - -. Here is what I see printed: onIncrement() onIncrement() onIncrement() onIncrement() onDecrement() What I expected was: onIncrement() onIncrement() onIncrement() onDecrement() onDecrement() onDecrement() Why is an extra onIncrement being called? And why is one onDecrement dropping on the floor? Deploying the app to iPhone Simulator does not repro this behavior (I see the six "correct" logs from iPhone Simulator).
Replies
9
Boosts
0
Views
941
Activity
Dec ’24
SwiftData Quakes Sample app decoding errors from null magnitudes
Hi! I believe there might be a small bug in the SwiftData Quakes Sample App.^1 The Quakes app requests a JSON feed from USGS.^2 What seems to be breaking is that apparently earthquake entities from USGS can return with null magnitudes. That is throwing errors from the decoder: struct GeoFeatureCollection: Decodable { let features: [Feature] struct Feature: Decodable { let properties: Properties let geometry: Geometry struct Properties: Decodable { let mag: Double let place: String let time: Date let code: String } struct Geometry: Decodable { let coordinates: [Double] } } } which is expecting mag to not be nil. Here is my workaround: struct GeoFeatureCollection: Decodable { let features: [Feature] struct Feature: Decodable { let properties: Properties let geometry: Geometry struct Properties: Decodable { let mag: Double? let place: String let time: Date let code: String } struct Geometry: Decodable { let coordinates: [Double] } } } And then: extension Quake { /// Creates a new quake instance from a decoded feature. convenience init(from feature: GeoFeatureCollection.Feature) { self.init( code: feature.properties.code, magnitude: feature.properties.mag ?? 0.0, time: feature.properties.time, name: feature.properties.place, longitude: feature.geometry.coordinates[0], latitude: feature.geometry.coordinates[1] ) } }
Replies
1
Boosts
0
Views
894
Activity
Dec ’24
How to resolve SwiftUI.DynamicProperty on MainActor compiler warning on 6.0?
Hi! I'm running into a warning from a SwiftUI.DynamicProperty on a 6.0 development build (swift-6.0-DEVELOPMENT-SNAPSHOT-2024-03-26-a). I am attempting to build a type (conforming to DynamicProperty) that should also be MainActor. This type with also need a custom update function. Here is a simple custom wrapper (handwaving over the orthogonal missing pieces) that shows the warning: import SwiftUI @MainActor struct MainProperty: DynamicProperty { // Main actor-isolated instance method 'update()' cannot be used to satisfy nonisolated protocol requirement; this is an error in the Swift 6 language mode @MainActor func update() { } } Is there anything I can do about that warning? Does the warning correctly imply that this will be a legit compiler error when 6.0 ships? I can find (at least) two examples of types adopting DynamicProperty from Apple that are also MainActor: FetchRequest and SectionedFetchRequest. What is confusing is that both FetchRequest^1 and SectionedFetchRequest^2 explicitly declare their update method to be MainActor. Is there anything missing from my Wrapper declaration that can get me what I'm looking for? Any more advice about that? Thanks!
Replies
4
Boosts
1
Views
1.3k
Activity
Nov ’24
Help understanding `SwiftUI.App` identity lifecycle and need for `SwiftUI.State`?
Hi! I have a stateful object that should be created in my app entry point and delivered through my component graph: @main @MainActor struct MyApp : App { @State private var myAppState = MyAppState() var body: some Scene { ... } } The MyApp is a struct value type… in a SwiftUI world that seems to imply it could "go away" and be recreated as the system sees appropriate. We see this with view components all the time (hence the State wrapper to help preserve our instance across the lifecycle of our identity)… but I'm wondering if this State wrapper is even necessary with an App entry point. Could this struct ever go away? Would there be any legit reasons that this struct should go away and recreate over one SwiftUI app lifecycle (other than terminating the app and starting a whole new process of course)? And what lifecycle is the SwiftUI.State tied to in this example? In a view component our SwiftUI.State is tied to our component identity. In this example… we are tied to app component identity? Is there ever going to be multiple legit app component identities live in the same process? I'm thinking I could just go ahead and keep using State as a best practice… but is this just overkill or is there a real best practice lurking under here? Any more ideas about that? Thanks!
Replies
2
Boosts
0
Views
576
Activity
Sep ’24
Unhandled exception finding default Directory URL '+[NSPersistentContainer defaultDirectoryURL] Could not conjure up a useful location for writing persistent stores.'
https://github.com/ordo-one/package-benchmark/issues/264 Hi! I am seeing this error specifically when I try to run the Ordo One benchmarks package with a SwiftData context. I am not sure if there is something missing in Ordo One or if this is some kind of legit SwiftData error. My benchmarks seem to be running fine even after the error prints. Any idea where that error might be coming from (and why I am not seeing that error when running SwiftData from other package executables)?
Replies
4
Boosts
0
Views
727
Activity
Aug ’24
ModelContext autosaveEnabled leading to crashes when SwiftUI App moves to background?
Hi! I'm investigating some crashes that seem to be related to ModelContext.autosaveEnabled^1. I don't have a very clean repro test case at this time… but I seem to be seeing crashes when a SwiftUI app moves to the background. I am testing an app built for macOS 14.6.1. I am building from Xcode_16_beta_5. My app is not using a mainContext. My app is building a ModelActor that is running on a background thread (off main). The modelContext inside my ModelActor is set with autosaveEnabled equal to true. The mutations on my state are not being explicitly saved (I am waiting for the system to save automatically). My guess (so far) is that transitioning into the background from SwiftUI is kicking off some kind of logic that is specifically being tied to the main thread… but this is causing problems when my modelContext is created from a background thread. My understanding was that ModelActor could help to defend against threading problems… but this might be a different problem that I did not expect. I am unblocked for now by turning off autosaveEnabled (and manually saving from my ModelActor). That fixes the crashes. Any more thoughts or insight about what could be causing these crashes when my app transitions into the background? Thanks! Thread 1 Queue : com.apple.main-thread (serial) #0 0x000000023108beb8 in ___lldb_unnamed_symbol2827 () #1 0x000000023108ef30 in ___lldb_unnamed_symbol2847 () #2 0x000000023108eca8 in ___lldb_unnamed_symbol2845 () #3 0x000000019bac6144 in __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ () #4 0x000000019bb5a3d8 in ___CFXRegistrationPost_block_invoke () #5 0x000000019bb5a320 in _CFXRegistrationPost () #6 0x000000019ba94678 in _CFXNotificationPost () #7 0x000000019cbb12c4 in -[NSNotificationCenter postNotificationName:object:userInfo:] () #8 0x000000019f489408 in -[NSApplication _handleDeactivateEvent:] () #9 0x000000019fb24380 in -[NSApplication(NSEventRouting) sendEvent:] () #10 0x000000019f771d9c in -[NSApplication _handleEvent:] () #11 0x000000019f322020 in -[NSApplication run] () #12 0x000000019f2f9240 in NSApplicationMain () #13 0x00000001c74c73b8 in ___lldb_unnamed_symbol83060 () #14 0x00000001c7c30ddc in ___lldb_unnamed_symbol132917 () #15 0x00000001c802be0c in static SwiftUI.App.main() -> () () Thread 5 Queue : NSManagedObjectContext 0x6000009c38e0 (serial) #0 0x000000019ba66f94 in constructBuffers () #1 0x000000019ba65e30 in _CFURLCreateWithURLString () #2 0x000000019bad6e7c in _CFURLComponentsCopyURLRelativeToURL () #3 0x000000019cbde864 in -[__NSConcreteURLComponents URL] () #4 0x000000019d3782f8 in -[NSURL(NSURL) initWithString:relativeToURL:encodingInvalidCharacters:] () #5 0x000000019cbdd4d4 in +[NSURL(NSURL) URLWithString:relativeToURL:] () #6 0x00000001a23feef0 in -[NSTemporaryObjectID URIRepresentation] () #7 0x00000002310e0878 in ___lldb_unnamed_symbol4176 () #8 0x00000002310ef480 in ___lldb_unnamed_symbol4401 () #9 0x00000002310eb6e0 in ___lldb_unnamed_symbol4385 () #10 0x00000002310a22b4 in ___lldb_unnamed_symbol3130 () #11 0x00000002310ed4e8 in ___lldb_unnamed_symbol4390 () #12 0x00000002310883dc in ___lldb_unnamed_symbol2799 () #13 0x0000000231087edc in ___lldb_unnamed_symbol2798 () #14 0x000000023109fd24 in ___lldb_unnamed_symbol3021 () #15 0x0000000231086acc in ___lldb_unnamed_symbol2784 () #16 0x00000001a2392144 in developerSubmittedBlockToNSManagedObjectContextPerform () #17 0x00000001a2392004 in -[NSManagedObjectContext performBlockAndWait:] () #18 0x00000002310879ac in ___lldb_unnamed_symbol2797 ()
Replies
1
Boosts
0
Views
651
Activity
Aug ’24
SwiftData Model with `updated` variable leads to wrong value being persisted.
Hi! I am seeing some unexpected behavior when attempting to create a Model instance with a variable named updated. I start with a simple Model: @Model final public class Item { var timestamp: Int var updated: Int public init(timestamp: Int = 1, updated: Int = 1) { self.timestamp = timestamp self.updated = updated } } I then attempt to create an item instance: func main() throws { let schema = Schema([Item.self]) let configuration = ModelConfiguration(isStoredInMemoryOnly: true) let container = try ModelContainer( for: schema, configurations: configuration ) let modelContext = ModelContext(container) let item = Item() print(item.timestamp) print(item.updated) } try main() The value of item.timestamp is printing as 1 and the value of item.updated is printing as 0. I have no idea what could be causing that to happen… why would both those values not be printing as 1? Is there some private API that is somehow colliding with the (public) updated variable and causing the item instance to report back with a value of 0? Is there documentation warning engineers that a variable named updated is off-limits and results in undefined behavior? I can fix that by renaming the variable: @Model final public class Item { var timestamp: Int var updatedTimestamp: Int public init() { self.timestamp = 1 self.updatedTimestamp = 1 } } I am unblocked on this (because renaming the variable seems to work fine)… but is there any insight on why this might be happening in the first place? I am building from Xcode_16_beta_5. Thanks!
Replies
2
Boosts
2
Views
518
Activity
Aug ’24