Swift is a powerful and intuitive programming language for Apple platforms and beyond.

Posts under Swift tag

200 Posts

Post

Replies

Boosts

Views

Activity

Programming Languages Resources
This topic area is about the programming languages themselves, not about any specific API or tool. If you have an API question, go to the top level and look for a subtopic for that API. If you have a question about Apple developer tools, start in the Developer Tools & Services topic. For Swift questions: If your question is about the SwiftUI framework, start in UI Frameworks > SwiftUI. If your question is specific to the Swift Playground app, ask over in Developer Tools & Services > Swift Playground If you’re interested in the Swift open source effort — that includes the evolution of the language, the open source tools and libraries, and Swift on non-Apple platforms — check out Swift Forums If your question is about the Swift language, that’s on topic for Programming Languages > Swift, but you might have more luck asking it in Swift Forums > Using Swift. General: Forums topic: Programming Languages Swift: Forums subtopic: Programming Languages > Swift Forums tags: Swift Developer > Swift website Swift Programming Language website The Swift Programming Language documentation Swift Forums website, and specifically Swift Forums > Using Swift Swift Package Index website Concurrency Resources, which covers Swift concurrency How to think properly about binding memory Swift Forums thread Other: Forums subtopic: Programming Languages > Generic Forums tags: Objective-C Programming with Objective-C archived documentation Objective-C Runtime documentation Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com"
0
0
2.8k
Oct ’25
Url Cache
Hi all, I have implemented a feature in my iOS application which checks the latest version available on App Store and if there is new update available it shows Pop to update the app. I am using this url for checki https://itunes.apple.com/lookup?bundleId= Issue: For some users this url returns old cached data which is previous version although new version is already live and i have verified this url directly via PostMan or other IDE.
1
0
27
1h
Default Actor Isolation - MainActor conflicts with Sendable
In Xcode project > Build Settings > Swift Compiler - Concurrency. When we have those settings : Approachable Concurrency - Yes Default Actor Isolation - MainActor A sendable struct without @Actor annotation will be stuck to @MainActor. But if we have a sendable struct, by principle, it should be used across Actors. To remediate the situation, we had to prefix the struct with nonisolated keyword. The setting "Default Actor Isolation - MainActor" should not add @MainActor to Sendables. Problem describe in : FB23264607
2
0
99
6h
Emoji rotated variation
Emoji are very convenient to be used instead of image, directly as String. In some cases, a variation to show them rotated (but still as String, not converted as image) would be useful. Examples may be arrows or flags if you need to show them floating from the top and not from the side of the pole. And I would declare: flag = "🇺🇸" or So the question; is it possible to generate new emoji as rotated initial emojis ? Or better, do such extensions already exist.
2
1
46
1d
Subclassing UISegmentedControl in Xcode 26 strange behavior
UIKit application. I have a UISegmentedControl which displays flags, using the emoji for the text of the segment (SegmentedControl defined in stroryboard). Depending app is in Portrait or Landscape, the segmented control is displayed vertically or horizontally. When horizontal, nothing to do, direct display from stroryboard, works as expected. When vertical (Portrait), I have to rotate the UISegmentedControl π/2. And To get the flags properly oriented, I rotate each image -π/2. That works fine when compiling with Xcode 16.4. But when compiling with Xcode 26.3, rotation of segments do not work. Here is the illustration, compile on target simulators 26.2 in both cases (3rd image explained below):                             Xcode 16.4           -               Xcode 26.3 subviews rotated   -     removed subviews rotation Now the code. I subclassed UISegmentedControl to draw at will. class SegmentedControlRotable: UISegmentedControl { @IBInspectable var vertical : Bool = false // IBInspectable is now ignored override func draw(_ rect: CGRect) { if vertical { self.transform = CGAffineTransform(rotationAngle: CGFloat.pi / 2.0) for subview in self.subviews { subview.transform = CGAffineTransform(rotationAngle: -CGFloat.pi / 2.0) // reverse rotate // 3rd picture: this line commented out. } } else { // does no change self.transform = CGAffineTransform(rotationAngle: 0.0) for subview in self.subviews { subview.transform = CGAffineTransform(rotationAngle: 0.0) } } } // More code with touchesEnded, works OK in both cases } In fact, with Xcode 26, segments are always drawn on an horizontal line. l I noticed that the structure of self.subviews is different. 19 subviews in Xcode 16, 12 in Xcode 26. I removed the rotation of subviews, and it's OK. Just flags are now vertical (as illustrated above). What do I miss ? How to rotate the subviews in Xcode 26 ?
0
0
46
1d
Sample Code with Swift 6
I find these sample projects quite valuable: https://developer.apple.com/documentation/widgetkit/emoji-rangers-supporting-live-activities-interactivity-and-animations https://developer.apple.com/documentation/coredata/sharing-core-data-objects-between-icloud-users . Both use Swift 5, and it is not trivial to adopt Swift 6 with them. Any plans to update them? What is best approach for adopting Swift 6 on such sample code?
5
0
628
2d
RegexBuilder infinite loop when nullable capture starts with NegativeLookahead
In Swift 6.4 or later, a RegexBuilder pattern can hang when an unbounded quantifier repeats a body that can match the empty string, where that body begins with NegativeLookahead. I've opened a corresponding issue and PR to resolve the issue in swift-experimental-string-processing. See below for a reproduction and a workaround. The regression affects apps running on OS 27 built with Xcode 27, which includes Swift 6.4. Running apps built with Xcode 27 on OS 26 or earlier demonstrates the expected behavior. Links: Issue: https://github.com/swiftlang/swift-experimental-string-processing/issues/865 PR: https://github.com/swiftlang/swift-experimental-string-processing/pull/866 FB23419149 and FB23179771 https://forums.swift.org/t/regexbuilder-infinite-loop-when-nullable-capture-starts-with-negativelookahead/87713 Reproduction In the reducer below, matching "A" repeatedly invokes the capture transform with an empty substring without advancing through the input. import RegexBuilder let regex = Regex { ZeroOrMore { Capture { NegativeLookahead { "a" } ZeroOrMore(.digit) } transform: { String($0) } // invoked repeatedly with "" } } _ = "A".matches(of: regex) // never returns Reduced string form: _ = try! Regex(#"(?:(?!a)\d*)*"#).firstMatch(in: "A") // never returns The issue is in the same forward-progress class as PR #851, which skips a nullable quantification's child subtree. Lookaround groups need the same treatment. The regression first appears in Swift 6.4-dev toolchains. I observed the issue in code running on iOS 27 beta 1 (24A5355q), then traced the regression to PR #849 in swift-experimental-string-processing. Workaround In the meantime, wrap the capture contents in Optionally { }: import RegexBuilder let digits = Regex { NegativeLookahead { "a" } ZeroOrMore(.digit) } let regex = Regex { ZeroOrMore { Capture { Optionally { digits } } transform: { String($0) } } } _ = "A".matches(of: regex)
1
1
133
2d
Customise UITabBar on iPadOS 26+
I'm building an app with a UISplitViewController as the base, with the main content being a UITabBarController. I'm targeting iOS 26+ and using UIKit. I've customised the tabbar on iOS to have a different font family and size, and used some custom images. Running the same app on iPad, the tabbar moves to the top of the screen, ignores ALL the appearance proxy settings and strips out the images. Its now just giant floating text. Also noticed in portrait mode when the side bar from the split view is open, it compresses the width of the tab bar down to only show 2 elements at a time, with this weird custom scroll thing to move to the rest of the tabs. If the text wasn't so massive, maybe it could fit more. I really hate every inch of this thing. Its looks ugly and functions bizarrely. Why does it ignore all the tabbar appearance settings, and how can I customise it to add icons back with smaller text? Ideally I don't want to use one of the hacks to force it to think its compact mode to bring back the old tabbar, as i'm relying on traits already to fix some SplitView annoyances and don't want those to break. But would love to have the old tab bar style. Are there any settings or toggles that I can use?
0
0
60
4d
UserDefaults.standard.integer(forKey: ) crashes the app with EXC_BAD_ACCESS (code=1, address=0x0)
With the 27 OSes using UserDefaults.standard.integer(forKey: ) can cause a crash with EXC_BAD_ACCESS (code=1, address=0x0) It has been seen on a Multiplatform app, up to now tested on iOS/iPadOS and visionOS 27 Beta 1. In our code we use UserDefaults.standard.integer(forKey: ) from a singleton called during the SwiftUI app init(), and we don't know yet if this is the only moment there is a crash as we can't go farther. The API should return 0 if it can't get a value. There is no reason the app should crash if the API conforms to its contract. Running the same code from Xcode on iOS 26 runs it without issue. FeedBack FB23310748
7
0
233
4d
Feedback on Foundation Models context management wrapper
I’ve been experimenting with Foundation Models and built a small Swift package that wraps LanguageModelSession with simple context management. The current approach checks the transcript token count using tokenCount(for:), compacts the transcript when it reaches a threshold, and retries once if exceededContextWindowSize is thrown. I’d appreciate feedback on whether this is a sensible use of Foundation Models APIs, especially around rebuilding a session from a compacted Transcript. GitHub: https://github.com/ricky-stone/FoundationContext
1
0
87
4d
Application Hangs with Nested LazyVStack When Accessibility Inspector is Active
Description I've encountered a consistent hang/freeze issue in SwiftUI applications when using nested LazyVStack containers with Accessibility Inspector (simulator) or VoiceOver (physical device) enabled. The application becomes completely unresponsive and must be force-quit. Importantly, this hang occurs in a minimal SwiftUI project with no third-party dependencies, suggesting this is a framework-level issue with the interaction between SwiftUI's lazy view lifecycle and the accessibility system. Reproduction Steps I've created a minimal reproduction project available here: https://github.com/pendo-io/SwiftUI_Hang_Reproduction To Reproduce: Create a SwiftUI view with the following nested LazyVStack structure: struct NestedLazyVStackView: View { @State private var outerSections: [Int] = [] @State private var innerRows: [Int: [Int]] = [:] var body: some View { ScrollView { LazyVStack(alignment: .leading, spacing: 24) { ForEach(outerSections, id: \.self) { section in VStack(alignment: .leading, spacing: 8) { Text("Section #\(section)") // Nested LazyVStack LazyVStack(alignment: .leading, spacing: 2) { ForEach(innerRows[section] ?? [], id: \.self) { row in Text("Section #\(section) - Row #\(row)") .onAppear { // Load more data when row appears loadMoreInner(section: section) } } } } .onAppear { // Load more sections when section appears loadMoreOuter() } } } } } } Enable Accessibility Inspector in iOS Simulator: Xcode → Open Developer Tool → Accessibility Inspector Select your running simulator Enable Inspection mode (eye icon) Navigate to the view and start scrolling Result: The application hangs and becomes unresponsive within a few seconds of scrolling Expected Behavior The application should remain responsive when Accessibility Inspector or VoiceOver is enabled, allowing users to scroll through nested lazy containers without freezing. Actual Behavior The application freezes/hangs completely CPU usage may spike The app must be force-quit to recover The hang occurs consistently and is reproducible Workaround 1: Replace inner LazyVStack with VStack LazyVStack { ForEach(...) { section in VStack { // ← Changed from LazyVStack ForEach(...) { row in ... } } } } Workaround 2: Embed in TabView TabView { NavigationStack { NestedLazyVStackView() // ← Same nested structure, but no hang } .tabItem { ... } } Interestingly, wrapping the entire navigation stack in a TabView prevents the hang entirely, even with the nested LazyVStack structure intact. Questions for Apple Is there a known issue with nested LazyVStack containers and accessibility traversal? Why does wrapping the view in a TabView prevent the hang? Are there recommended patterns for using nested lazy containers with accessibility support? Is this a timing issue, a deadlock, or an infinite loop in the accessibility system? Why that happens? Reproduction Project A complete, minimal reproduction project is available at: https://github.com/pendo-io/SwiftUI_Hang_Reproduction
8
0
616
5d
Are there any ways to prevent app record/capture on macOS
I'm looking for a way to prevent my app from displaying in screenshots and screen recordings. There appears to be plenty of options for UIKit/iOS but nothing I can find for macOS. userDidTakeScreenshotNotification @Environment(.sceneCaptureState) private var captureState Obviously it's possible though as I remember back in the day you couldn't take screenshots of the DVD Player etc.
0
0
71
5d
Does @IBSegueAction still not work for AppKit relationship segues from NSWindowController?
I’m working on a storyboard-based AppKit application that uses an NSWindowController containing an NSSplitViewController with multiple child view controllers. The hierarchy is roughly: NSWindowController └── NSSplitViewController ├── NSViewController ├── NSViewController └── NSViewController I am trying to provide dependencies during storyboard instantiation using either @IBSegueAction or instantiateInitialController(creator:), rather than configuring everything after initialisation. What I attempted I added custom initialisers to my view controllers so I can pass dependencies at creation time: class SplitViewController: NSSplitViewController { let dependency: Dependency init?(coder: NSCoder, dependency: Dependency) { self.dependency = dependency super.init(coder: coder) } required init?(coder: NSCoder) { print("init(coder:) was called") fatalError("init(coder:) is not supported") } } I then attempted to intercept storyboard instantiation using @IBSegueAction, trying it in both the window controller and the split view controller: @IBSegueAction func makeSplitViewController(_ coder: NSCoder) -> NSSplitViewController? { SplitViewController(coder: coder, dependency: dependency) } I also tried attaching the segue action at different points in the storyboard, but the behaviour did not change. Observed behaviour Regardless of where I place the segue action, AppKit still appears to call: required init?(coder: NSCoder) This means my custom initialiser is never used for the split view controller or its children. Background reference I found this older known issue in the Xcode 11 release notes: “A Segue Action on a relationship segue between a NSWindowController and a View Controller is currently not supported and ignored. (48252727)” This suggests that, at least historically, AppKit relationship segues ignored segue actions entirely. Has this limitation since been fixed in modern Xcode/macOS SDK releases, or are relationship segues involving NSWindowController still incompatible with @IBSegueAction? More generally, what is the intended way to provide dependencies to an NSSplitViewController and its child view controllers in a storyboard-based AppKit application? I am also unclear whether instantiateInitialController(creator:) participates in the creation of container hierarchies like split view controllers, or only top-level controllers.
2
0
462
6d
SwiftUI Equivalent of Nested Scroll Connection for Collapsing Profile Screens
I'm trying to build a profile-style screen similar to X (Twitter), Instagram, or YouTube. The layout is roughly: ┌──────────────────────────┐ │ Profile Header │ │ Cover image │ │ Avatar │ │ Bio / Stats │ └──────────────────────────┘ ┌──────────────────────────┐ │ Tab Bar │ │ Posts | Media | Likes │ └──────────────────────────┘ ┌──────────────────────────┐ │ Tab Content │ │ │ │ ScrollView / List │ │ OR │ │ Empty State VStack │ │ │ └──────────────────────────┘ Requirements: The profile header should collapse while scrolling up. The tab bar should remain pinned. Once the header is fully collapsed, the active tab's scroll view should start scrolling. While scrolling down, the active tab should scroll back to the top first, then the header should expand. Some tabs may contain: ScrollView + LazyVStack List a non-scrollable VStack (for empty states) The behavior should remain consistent regardless of which tab is active. This feels very similar to Jetpack Compose's NestedScrollConnection, where parent and child scroll containers can cooperatively consume scroll deltas. In SwiftUI, I have explored: ScrollView GeometryReader PreferenceKey Scroll offset tracking Custom UIScrollView wrappers A UIViewControllerRepresentable approach that intercepts pan gestures and coordinates scrolling manually However, I haven't found a SwiftUI-native way for a parent container and child scroll view to negotiate scroll consumption. My questions are: Does SwiftUI provide any equivalent to Compose's NestedScrollConnection? Is there a recommended way to implement this profile-screen pattern purely in SwiftUI? How are people handling cases where some tabs contain scrollable content while other tabs contain only static content? Is bridging to UIKit currently the only practical solution for this kind of coordinated scrolling behavior? Any guidance or examples would be greatly appreciated.
0
0
72
6d
app groups user defaults are not returning values in macOS27 beta
Hi, I have a app group registered in mac os app called gorup.com.company.app and i am saving the key/values in userdefaults to this with suitname. within the mac os app the group userdedaults write/read are working fine. I have a switt cli app with same app group registered in the code signing entitilement for the swit cli app. trying to read the group user default key value registered in mac os app in swift cli app returning no value. this was working fine with macOS 26. Is there some changes have been made in macos 27 in regaard to this?
6
0
217
6d
Metadata in Video stripped by Share Sheet / Airdrop
I have an application which records video along with some custom metadata and a chapter track. The resultant video is stored in the Camera Roll. When sharing the video via the Share Sheet or AirDrop, the metadata track is stripped entirely (the chapter markers are preserved) Sharing via AirDrop with the "All Photos Data" option does include the metadata track, as does copying from the device with Image Capture but this is a bad user experience as the user must remember to explicitly select this option, and the filename is lost when sending this way. I have also tried various other approaches (such as encoding my metadata in a subtitle track, which I didn't expect to be stripped as it's an accessibility concern) but it's also removed. Essentially I am looking for a definitive list of things that are not stripped or if there's a way to encode a track in some way to indicate it should be preserved. The metadata is added via AVTimedMetadataGroup containing one AVMutableMetadataItem which has its value as a JSON string. I took a different approach with the Chapter Marker track (mainly because I did it first in a completely different way and didn't rework it when I added the other track). I post-process these after the video is recorded, and add them with addMutableTrack and then addTrackAssociation(to: chapterTrack, type: .chapterList) but I don't think that's the reason the chapter track persists where the custom metadata does not as other tests with video files from other sources containing subtitles etc also had their subtitle data stripped. tl;dr I record videos with metadata that I want to be able to share via Share Sheet and AirDrop, what am I doing wrong?
2
0
818
1w
DProvenanceKit: Reasoning observability for AI systems in Swift
Hi everyone, I've been working on a problem that I think many of us building AI in Swift are facing: how do you debug why an AI agent behaves differently between runs? Traditional logging tells you what happened. But when a model skips a step, changes its reasoning order, or produces a different output with identical input — you're left staring at walls of logs with no clear answer to why. I've released DProvenanceKit — a reasoning observability framework for Swift that lets you: Record every reasoning step an agent takes (non-blocking, async-safe) Query for reasoning patterns ("find runs where X happened but Y didn't") Diff two executions to see structural differences Detect regressions automatically with rule-based validation Think of it as Git for AI logic. Example: Swift // Record an execution try await DProvenanceKit.run(contextID: "case-123", store: store) { DProvenanceKit.record(.documentEvaluated(documentID: "DocA", score: 0.95)) DProvenanceKit.record(.conflictDetected(reason: "timeline_inconsistency")) DProvenanceKit.record(.finalDecisionMade(approved: false)) } // Query for suspicious patterns let suspiciousRuns = try await store.queryRuns( TraceQueryDSL() .requiring(step: "conflictDetected") .missing(step: "documentEvaluated") // Find runs where conflict was reported but no docs evaluated ) // Diff two runs let diff = engine.diff(base: runA, comparison: runB) print(diff.changes) // See exactly which steps appeared, disappeared, or moved The design: Built specifically for on-device AI (macOS/iOS) with Apple Foundation Models, MLX, or Core ML Non-blocking recording (touches only in-memory buffer) Durable, crash-safe persistence with SQLite WAL Works with async/await context propagation Status: Experimental (core engine complete, actively evolving). Free for development/testing under BSL 1.1. GitHub: https://github.com/Therealdk8890/DProvenanceKit I'm curious if this resonates with anyone here building AI in Swift. What debugging/observability challenges are you facing with AI systems?
0
0
87
1w
Supported way for iOS Safari Web Extension to hand off captured data to containing app for processing?
In 2018, Apple staff noted that Safari App Extensions had no direct API to communicate with the containing app, and suggested app groups or opening a custom URL scheme as workarounds. On iOS Safari Web Extensions, app groups work for persistence, but opening the containing app from the native extension/background flow does not appear reliable. iOS launch policy seems to require a direct user gesture, and I have not found a documented way for the extension flow to reliably continue into the containing app. Is there a supported iOS architecture for completing an extension-initiated workflow in the containing app, or is the intended model to persist data and require the user to manually open the app? My current architecture is: JavaScript in the Safari Web Extension extracts article content from the page. The native Extension Handler receives that content via native messaging. The Extension Handler writes an encoded request into the App Group container. The containing app watches the App Group container using DispatchSource.makeFileSystemObjectSource and processes new requests. This works on macOS. It also works on iOS when the containing app is already running. The problem is that on iOS, if the containing app is not already running, there is no app process to observe the filesystem event or process the request. I have tried treating the Extension Handler as the place to do more work, but in practice it seems suited only for short-lived relay/persistence work. It is not a reliable place for my app’s main processing pipeline, which includes rendering article content and uploading it to a third-party service. My app is a Safari-native “read later” style tool that uploads simplified articles to the reMarkable Cloud. The containing app contains most of the functionality: SwiftUI UI, WebKit/WebPage rendering, account/cloud logic, and upload orchestration. The Safari extension captures the article, but the app needs to run to complete the user-visible workflow. From a user’s perspective, tapping the Safari extension toolbar button is the action that initiates the workflow. Is there any supported way for that user-initiated extension action to launch or wake the containing iOS app so it can process pending App Group requests? Or should Safari Web Extensions on iOS be designed only to persist work and then ask the user to manually open the containing app? If manual app launch is the intended model, it would be helpful for the documentation to state this explicitly. The current tripartite model strongly suggests that the JavaScript extension, native handler, and containing app can collaborate as parts of one workflow, but on iOS the containing app appears to be available only out-of-band unless already running.
0
0
165
1w
Xcode 27: spike in "Class X is implemented in both" warnings
Anyone else seeing a lot more "Class X is implemented in both ..." warnings on Xcode 27 than on Xcode 26? Same source, same flags, the count goes from a handful to a couple thousand, and some now correlate with real crashes (cast failures, missing protocol conformances) instead of the usual harmless first-wins behavior. Is this a known change in Swift 6.4 / Xcode 27? Is there a new flag I should be passing? Any suggestions welcome.
3
0
229
1w
Xcode 26.4 and 26.3: Swift compiler crashes during archive with iOS 17 deployment target
I submitted this to Feedback Assistant as FB22331090 and wanted to share a minimal reproducible example here in case others are seeing the same issue. Environment: Xcode 26.4 or Xcode 26.3 Apple Swift version 6.3 (swiftlang-6.3.0.123.5 clang-2100.0.123.102) Effective Swift language version 5.10 Deployment target: iOS 17.0 The sample app builds successfully for normal development use, but archive fails. The crash happens during optimization in EarlyPerfInliner while compiling the synthesized deinit of a nested generic Coordinator class. The coordinator stores a UIHostingController. Minimal reproducer: import SwiftUI struct ReproView<Content: View>: UIViewRepresentable { let content: Content func makeUIView(context: Context) -> UIView { context.coordinator.host.view } func updateUIView(_ uiView: UIView, context: Context) { context.coordinator.host.rootView = content } func makeCoordinator() -> Coordinator { Coordinator(content: content) } final class Coordinator { let host: UIHostingController<Content> init(content: Content) { host = UIHostingController(rootView: content) } } } Used from ContentView like this: ReproView(content: Text("Hello")) Steps: Create a new SwiftUI iOS app. Set deployment target to iOS 17.0. Add the code above. Archive. Expected result: Archive succeeds, or the compiler emits a normal diagnostic. Actual result: The Swift compiler crashes and prints: "Please submit a bug report" "While running pass ... SILFunctionTransform 'EarlyPerfInliner'" The crash occurs while compiling the synthesized deinit for ReproView.Coordinator. Relevant log lines from my archive log: line 209: Please submit a bug report line 215: While running pass ... EarlyPerfInliner line 216: for 'deinit' at ReproView.swift:19:17 One more detail: The same sample archived successfully when the deployment target was higher. Lowering the deployment target to iOS 17.0 made the archive crash reproducible. This may be related to another forum thread about release-only compiler crashes, but the reproducer here is different: this one uses a generic UIViewRepresentable with a nested Coordinator storing UIHostingController.
3
1
391
1w
Programming Languages Resources
This topic area is about the programming languages themselves, not about any specific API or tool. If you have an API question, go to the top level and look for a subtopic for that API. If you have a question about Apple developer tools, start in the Developer Tools & Services topic. For Swift questions: If your question is about the SwiftUI framework, start in UI Frameworks > SwiftUI. If your question is specific to the Swift Playground app, ask over in Developer Tools & Services > Swift Playground If you’re interested in the Swift open source effort — that includes the evolution of the language, the open source tools and libraries, and Swift on non-Apple platforms — check out Swift Forums If your question is about the Swift language, that’s on topic for Programming Languages > Swift, but you might have more luck asking it in Swift Forums > Using Swift. General: Forums topic: Programming Languages Swift: Forums subtopic: Programming Languages > Swift Forums tags: Swift Developer > Swift website Swift Programming Language website The Swift Programming Language documentation Swift Forums website, and specifically Swift Forums > Using Swift Swift Package Index website Concurrency Resources, which covers Swift concurrency How to think properly about binding memory Swift Forums thread Other: Forums subtopic: Programming Languages > Generic Forums tags: Objective-C Programming with Objective-C archived documentation Objective-C Runtime documentation Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com"
Replies
0
Boosts
0
Views
2.8k
Activity
Oct ’25
Url Cache
Hi all, I have implemented a feature in my iOS application which checks the latest version available on App Store and if there is new update available it shows Pop to update the app. I am using this url for checki https://itunes.apple.com/lookup?bundleId= Issue: For some users this url returns old cached data which is previous version although new version is already live and i have verified this url directly via PostMan or other IDE.
Replies
1
Boosts
0
Views
27
Activity
1h
Default Actor Isolation - MainActor conflicts with Sendable
In Xcode project > Build Settings > Swift Compiler - Concurrency. When we have those settings : Approachable Concurrency - Yes Default Actor Isolation - MainActor A sendable struct without @Actor annotation will be stuck to @MainActor. But if we have a sendable struct, by principle, it should be used across Actors. To remediate the situation, we had to prefix the struct with nonisolated keyword. The setting "Default Actor Isolation - MainActor" should not add @MainActor to Sendables. Problem describe in : FB23264607
Replies
2
Boosts
0
Views
99
Activity
6h
Mesh boolean subtraction operation with SceneKit/RealityKit
I ma trying to figure out if there is a Boolean subtraction functionality native in SceneKit or RealityKit. Simple operation like cutting a hole in a box from a sphere. If not, are there any libraries (free) that I can look into?
Replies
3
Boosts
0
Views
1.9k
Activity
6h
Emoji rotated variation
Emoji are very convenient to be used instead of image, directly as String. In some cases, a variation to show them rotated (but still as String, not converted as image) would be useful. Examples may be arrows or flags if you need to show them floating from the top and not from the side of the pole. And I would declare: flag = "🇺🇸" or So the question; is it possible to generate new emoji as rotated initial emojis ? Or better, do such extensions already exist.
Replies
2
Boosts
1
Views
46
Activity
1d
Subclassing UISegmentedControl in Xcode 26 strange behavior
UIKit application. I have a UISegmentedControl which displays flags, using the emoji for the text of the segment (SegmentedControl defined in stroryboard). Depending app is in Portrait or Landscape, the segmented control is displayed vertically or horizontally. When horizontal, nothing to do, direct display from stroryboard, works as expected. When vertical (Portrait), I have to rotate the UISegmentedControl π/2. And To get the flags properly oriented, I rotate each image -π/2. That works fine when compiling with Xcode 16.4. But when compiling with Xcode 26.3, rotation of segments do not work. Here is the illustration, compile on target simulators 26.2 in both cases (3rd image explained below):                             Xcode 16.4           -               Xcode 26.3 subviews rotated   -     removed subviews rotation Now the code. I subclassed UISegmentedControl to draw at will. class SegmentedControlRotable: UISegmentedControl { @IBInspectable var vertical : Bool = false // IBInspectable is now ignored override func draw(_ rect: CGRect) { if vertical { self.transform = CGAffineTransform(rotationAngle: CGFloat.pi / 2.0) for subview in self.subviews { subview.transform = CGAffineTransform(rotationAngle: -CGFloat.pi / 2.0) // reverse rotate // 3rd picture: this line commented out. } } else { // does no change self.transform = CGAffineTransform(rotationAngle: 0.0) for subview in self.subviews { subview.transform = CGAffineTransform(rotationAngle: 0.0) } } } // More code with touchesEnded, works OK in both cases } In fact, with Xcode 26, segments are always drawn on an horizontal line. l I noticed that the structure of self.subviews is different. 19 subviews in Xcode 16, 12 in Xcode 26. I removed the rotation of subviews, and it's OK. Just flags are now vertical (as illustrated above). What do I miss ? How to rotate the subviews in Xcode 26 ?
Replies
0
Boosts
0
Views
46
Activity
1d
Sample Code with Swift 6
I find these sample projects quite valuable: https://developer.apple.com/documentation/widgetkit/emoji-rangers-supporting-live-activities-interactivity-and-animations https://developer.apple.com/documentation/coredata/sharing-core-data-objects-between-icloud-users . Both use Swift 5, and it is not trivial to adopt Swift 6 with them. Any plans to update them? What is best approach for adopting Swift 6 on such sample code?
Replies
5
Boosts
0
Views
628
Activity
2d
RegexBuilder infinite loop when nullable capture starts with NegativeLookahead
In Swift 6.4 or later, a RegexBuilder pattern can hang when an unbounded quantifier repeats a body that can match the empty string, where that body begins with NegativeLookahead. I've opened a corresponding issue and PR to resolve the issue in swift-experimental-string-processing. See below for a reproduction and a workaround. The regression affects apps running on OS 27 built with Xcode 27, which includes Swift 6.4. Running apps built with Xcode 27 on OS 26 or earlier demonstrates the expected behavior. Links: Issue: https://github.com/swiftlang/swift-experimental-string-processing/issues/865 PR: https://github.com/swiftlang/swift-experimental-string-processing/pull/866 FB23419149 and FB23179771 https://forums.swift.org/t/regexbuilder-infinite-loop-when-nullable-capture-starts-with-negativelookahead/87713 Reproduction In the reducer below, matching "A" repeatedly invokes the capture transform with an empty substring without advancing through the input. import RegexBuilder let regex = Regex { ZeroOrMore { Capture { NegativeLookahead { "a" } ZeroOrMore(.digit) } transform: { String($0) } // invoked repeatedly with "" } } _ = "A".matches(of: regex) // never returns Reduced string form: _ = try! Regex(#"(?:(?!a)\d*)*"#).firstMatch(in: "A") // never returns The issue is in the same forward-progress class as PR #851, which skips a nullable quantification's child subtree. Lookaround groups need the same treatment. The regression first appears in Swift 6.4-dev toolchains. I observed the issue in code running on iOS 27 beta 1 (24A5355q), then traced the regression to PR #849 in swift-experimental-string-processing. Workaround In the meantime, wrap the capture contents in Optionally { }: import RegexBuilder let digits = Regex { NegativeLookahead { "a" } ZeroOrMore(.digit) } let regex = Regex { ZeroOrMore { Capture { Optionally { digits } } transform: { String($0) } } } _ = "A".matches(of: regex)
Replies
1
Boosts
1
Views
133
Activity
2d
Customise UITabBar on iPadOS 26+
I'm building an app with a UISplitViewController as the base, with the main content being a UITabBarController. I'm targeting iOS 26+ and using UIKit. I've customised the tabbar on iOS to have a different font family and size, and used some custom images. Running the same app on iPad, the tabbar moves to the top of the screen, ignores ALL the appearance proxy settings and strips out the images. Its now just giant floating text. Also noticed in portrait mode when the side bar from the split view is open, it compresses the width of the tab bar down to only show 2 elements at a time, with this weird custom scroll thing to move to the rest of the tabs. If the text wasn't so massive, maybe it could fit more. I really hate every inch of this thing. Its looks ugly and functions bizarrely. Why does it ignore all the tabbar appearance settings, and how can I customise it to add icons back with smaller text? Ideally I don't want to use one of the hacks to force it to think its compact mode to bring back the old tabbar, as i'm relying on traits already to fix some SplitView annoyances and don't want those to break. But would love to have the old tab bar style. Are there any settings or toggles that I can use?
Replies
0
Boosts
0
Views
60
Activity
4d
UserDefaults.standard.integer(forKey: ) crashes the app with EXC_BAD_ACCESS (code=1, address=0x0)
With the 27 OSes using UserDefaults.standard.integer(forKey: ) can cause a crash with EXC_BAD_ACCESS (code=1, address=0x0) It has been seen on a Multiplatform app, up to now tested on iOS/iPadOS and visionOS 27 Beta 1. In our code we use UserDefaults.standard.integer(forKey: ) from a singleton called during the SwiftUI app init(), and we don't know yet if this is the only moment there is a crash as we can't go farther. The API should return 0 if it can't get a value. There is no reason the app should crash if the API conforms to its contract. Running the same code from Xcode on iOS 26 runs it without issue. FeedBack FB23310748
Replies
7
Boosts
0
Views
233
Activity
4d
Feedback on Foundation Models context management wrapper
I’ve been experimenting with Foundation Models and built a small Swift package that wraps LanguageModelSession with simple context management. The current approach checks the transcript token count using tokenCount(for:), compacts the transcript when it reaches a threshold, and retries once if exceededContextWindowSize is thrown. I’d appreciate feedback on whether this is a sensible use of Foundation Models APIs, especially around rebuilding a session from a compacted Transcript. GitHub: https://github.com/ricky-stone/FoundationContext
Replies
1
Boosts
0
Views
87
Activity
4d
Application Hangs with Nested LazyVStack When Accessibility Inspector is Active
Description I've encountered a consistent hang/freeze issue in SwiftUI applications when using nested LazyVStack containers with Accessibility Inspector (simulator) or VoiceOver (physical device) enabled. The application becomes completely unresponsive and must be force-quit. Importantly, this hang occurs in a minimal SwiftUI project with no third-party dependencies, suggesting this is a framework-level issue with the interaction between SwiftUI's lazy view lifecycle and the accessibility system. Reproduction Steps I've created a minimal reproduction project available here: https://github.com/pendo-io/SwiftUI_Hang_Reproduction To Reproduce: Create a SwiftUI view with the following nested LazyVStack structure: struct NestedLazyVStackView: View { @State private var outerSections: [Int] = [] @State private var innerRows: [Int: [Int]] = [:] var body: some View { ScrollView { LazyVStack(alignment: .leading, spacing: 24) { ForEach(outerSections, id: \.self) { section in VStack(alignment: .leading, spacing: 8) { Text("Section #\(section)") // Nested LazyVStack LazyVStack(alignment: .leading, spacing: 2) { ForEach(innerRows[section] ?? [], id: \.self) { row in Text("Section #\(section) - Row #\(row)") .onAppear { // Load more data when row appears loadMoreInner(section: section) } } } } .onAppear { // Load more sections when section appears loadMoreOuter() } } } } } } Enable Accessibility Inspector in iOS Simulator: Xcode → Open Developer Tool → Accessibility Inspector Select your running simulator Enable Inspection mode (eye icon) Navigate to the view and start scrolling Result: The application hangs and becomes unresponsive within a few seconds of scrolling Expected Behavior The application should remain responsive when Accessibility Inspector or VoiceOver is enabled, allowing users to scroll through nested lazy containers without freezing. Actual Behavior The application freezes/hangs completely CPU usage may spike The app must be force-quit to recover The hang occurs consistently and is reproducible Workaround 1: Replace inner LazyVStack with VStack LazyVStack { ForEach(...) { section in VStack { // ← Changed from LazyVStack ForEach(...) { row in ... } } } } Workaround 2: Embed in TabView TabView { NavigationStack { NestedLazyVStackView() // ← Same nested structure, but no hang } .tabItem { ... } } Interestingly, wrapping the entire navigation stack in a TabView prevents the hang entirely, even with the nested LazyVStack structure intact. Questions for Apple Is there a known issue with nested LazyVStack containers and accessibility traversal? Why does wrapping the view in a TabView prevent the hang? Are there recommended patterns for using nested lazy containers with accessibility support? Is this a timing issue, a deadlock, or an infinite loop in the accessibility system? Why that happens? Reproduction Project A complete, minimal reproduction project is available at: https://github.com/pendo-io/SwiftUI_Hang_Reproduction
Replies
8
Boosts
0
Views
616
Activity
5d
Are there any ways to prevent app record/capture on macOS
I'm looking for a way to prevent my app from displaying in screenshots and screen recordings. There appears to be plenty of options for UIKit/iOS but nothing I can find for macOS. userDidTakeScreenshotNotification @Environment(.sceneCaptureState) private var captureState Obviously it's possible though as I remember back in the day you couldn't take screenshots of the DVD Player etc.
Replies
0
Boosts
0
Views
71
Activity
5d
Does @IBSegueAction still not work for AppKit relationship segues from NSWindowController?
I’m working on a storyboard-based AppKit application that uses an NSWindowController containing an NSSplitViewController with multiple child view controllers. The hierarchy is roughly: NSWindowController └── NSSplitViewController ├── NSViewController ├── NSViewController └── NSViewController I am trying to provide dependencies during storyboard instantiation using either @IBSegueAction or instantiateInitialController(creator:), rather than configuring everything after initialisation. What I attempted I added custom initialisers to my view controllers so I can pass dependencies at creation time: class SplitViewController: NSSplitViewController { let dependency: Dependency init?(coder: NSCoder, dependency: Dependency) { self.dependency = dependency super.init(coder: coder) } required init?(coder: NSCoder) { print("init(coder:) was called") fatalError("init(coder:) is not supported") } } I then attempted to intercept storyboard instantiation using @IBSegueAction, trying it in both the window controller and the split view controller: @IBSegueAction func makeSplitViewController(_ coder: NSCoder) -> NSSplitViewController? { SplitViewController(coder: coder, dependency: dependency) } I also tried attaching the segue action at different points in the storyboard, but the behaviour did not change. Observed behaviour Regardless of where I place the segue action, AppKit still appears to call: required init?(coder: NSCoder) This means my custom initialiser is never used for the split view controller or its children. Background reference I found this older known issue in the Xcode 11 release notes: “A Segue Action on a relationship segue between a NSWindowController and a View Controller is currently not supported and ignored. (48252727)” This suggests that, at least historically, AppKit relationship segues ignored segue actions entirely. Has this limitation since been fixed in modern Xcode/macOS SDK releases, or are relationship segues involving NSWindowController still incompatible with @IBSegueAction? More generally, what is the intended way to provide dependencies to an NSSplitViewController and its child view controllers in a storyboard-based AppKit application? I am also unclear whether instantiateInitialController(creator:) participates in the creation of container hierarchies like split view controllers, or only top-level controllers.
Replies
2
Boosts
0
Views
462
Activity
6d
SwiftUI Equivalent of Nested Scroll Connection for Collapsing Profile Screens
I'm trying to build a profile-style screen similar to X (Twitter), Instagram, or YouTube. The layout is roughly: ┌──────────────────────────┐ │ Profile Header │ │ Cover image │ │ Avatar │ │ Bio / Stats │ └──────────────────────────┘ ┌──────────────────────────┐ │ Tab Bar │ │ Posts | Media | Likes │ └──────────────────────────┘ ┌──────────────────────────┐ │ Tab Content │ │ │ │ ScrollView / List │ │ OR │ │ Empty State VStack │ │ │ └──────────────────────────┘ Requirements: The profile header should collapse while scrolling up. The tab bar should remain pinned. Once the header is fully collapsed, the active tab's scroll view should start scrolling. While scrolling down, the active tab should scroll back to the top first, then the header should expand. Some tabs may contain: ScrollView + LazyVStack List a non-scrollable VStack (for empty states) The behavior should remain consistent regardless of which tab is active. This feels very similar to Jetpack Compose's NestedScrollConnection, where parent and child scroll containers can cooperatively consume scroll deltas. In SwiftUI, I have explored: ScrollView GeometryReader PreferenceKey Scroll offset tracking Custom UIScrollView wrappers A UIViewControllerRepresentable approach that intercepts pan gestures and coordinates scrolling manually However, I haven't found a SwiftUI-native way for a parent container and child scroll view to negotiate scroll consumption. My questions are: Does SwiftUI provide any equivalent to Compose's NestedScrollConnection? Is there a recommended way to implement this profile-screen pattern purely in SwiftUI? How are people handling cases where some tabs contain scrollable content while other tabs contain only static content? Is bridging to UIKit currently the only practical solution for this kind of coordinated scrolling behavior? Any guidance or examples would be greatly appreciated.
Replies
0
Boosts
0
Views
72
Activity
6d
app groups user defaults are not returning values in macOS27 beta
Hi, I have a app group registered in mac os app called gorup.com.company.app and i am saving the key/values in userdefaults to this with suitname. within the mac os app the group userdedaults write/read are working fine. I have a switt cli app with same app group registered in the code signing entitilement for the swit cli app. trying to read the group user default key value registered in mac os app in swift cli app returning no value. this was working fine with macOS 26. Is there some changes have been made in macos 27 in regaard to this?
Replies
6
Boosts
0
Views
217
Activity
6d
Metadata in Video stripped by Share Sheet / Airdrop
I have an application which records video along with some custom metadata and a chapter track. The resultant video is stored in the Camera Roll. When sharing the video via the Share Sheet or AirDrop, the metadata track is stripped entirely (the chapter markers are preserved) Sharing via AirDrop with the "All Photos Data" option does include the metadata track, as does copying from the device with Image Capture but this is a bad user experience as the user must remember to explicitly select this option, and the filename is lost when sending this way. I have also tried various other approaches (such as encoding my metadata in a subtitle track, which I didn't expect to be stripped as it's an accessibility concern) but it's also removed. Essentially I am looking for a definitive list of things that are not stripped or if there's a way to encode a track in some way to indicate it should be preserved. The metadata is added via AVTimedMetadataGroup containing one AVMutableMetadataItem which has its value as a JSON string. I took a different approach with the Chapter Marker track (mainly because I did it first in a completely different way and didn't rework it when I added the other track). I post-process these after the video is recorded, and add them with addMutableTrack and then addTrackAssociation(to: chapterTrack, type: .chapterList) but I don't think that's the reason the chapter track persists where the custom metadata does not as other tests with video files from other sources containing subtitles etc also had their subtitle data stripped. tl;dr I record videos with metadata that I want to be able to share via Share Sheet and AirDrop, what am I doing wrong?
Replies
2
Boosts
0
Views
818
Activity
1w
DProvenanceKit: Reasoning observability for AI systems in Swift
Hi everyone, I've been working on a problem that I think many of us building AI in Swift are facing: how do you debug why an AI agent behaves differently between runs? Traditional logging tells you what happened. But when a model skips a step, changes its reasoning order, or produces a different output with identical input — you're left staring at walls of logs with no clear answer to why. I've released DProvenanceKit — a reasoning observability framework for Swift that lets you: Record every reasoning step an agent takes (non-blocking, async-safe) Query for reasoning patterns ("find runs where X happened but Y didn't") Diff two executions to see structural differences Detect regressions automatically with rule-based validation Think of it as Git for AI logic. Example: Swift // Record an execution try await DProvenanceKit.run(contextID: "case-123", store: store) { DProvenanceKit.record(.documentEvaluated(documentID: "DocA", score: 0.95)) DProvenanceKit.record(.conflictDetected(reason: "timeline_inconsistency")) DProvenanceKit.record(.finalDecisionMade(approved: false)) } // Query for suspicious patterns let suspiciousRuns = try await store.queryRuns( TraceQueryDSL() .requiring(step: "conflictDetected") .missing(step: "documentEvaluated") // Find runs where conflict was reported but no docs evaluated ) // Diff two runs let diff = engine.diff(base: runA, comparison: runB) print(diff.changes) // See exactly which steps appeared, disappeared, or moved The design: Built specifically for on-device AI (macOS/iOS) with Apple Foundation Models, MLX, or Core ML Non-blocking recording (touches only in-memory buffer) Durable, crash-safe persistence with SQLite WAL Works with async/await context propagation Status: Experimental (core engine complete, actively evolving). Free for development/testing under BSL 1.1. GitHub: https://github.com/Therealdk8890/DProvenanceKit I'm curious if this resonates with anyone here building AI in Swift. What debugging/observability challenges are you facing with AI systems?
Replies
0
Boosts
0
Views
87
Activity
1w
Supported way for iOS Safari Web Extension to hand off captured data to containing app for processing?
In 2018, Apple staff noted that Safari App Extensions had no direct API to communicate with the containing app, and suggested app groups or opening a custom URL scheme as workarounds. On iOS Safari Web Extensions, app groups work for persistence, but opening the containing app from the native extension/background flow does not appear reliable. iOS launch policy seems to require a direct user gesture, and I have not found a documented way for the extension flow to reliably continue into the containing app. Is there a supported iOS architecture for completing an extension-initiated workflow in the containing app, or is the intended model to persist data and require the user to manually open the app? My current architecture is: JavaScript in the Safari Web Extension extracts article content from the page. The native Extension Handler receives that content via native messaging. The Extension Handler writes an encoded request into the App Group container. The containing app watches the App Group container using DispatchSource.makeFileSystemObjectSource and processes new requests. This works on macOS. It also works on iOS when the containing app is already running. The problem is that on iOS, if the containing app is not already running, there is no app process to observe the filesystem event or process the request. I have tried treating the Extension Handler as the place to do more work, but in practice it seems suited only for short-lived relay/persistence work. It is not a reliable place for my app’s main processing pipeline, which includes rendering article content and uploading it to a third-party service. My app is a Safari-native “read later” style tool that uploads simplified articles to the reMarkable Cloud. The containing app contains most of the functionality: SwiftUI UI, WebKit/WebPage rendering, account/cloud logic, and upload orchestration. The Safari extension captures the article, but the app needs to run to complete the user-visible workflow. From a user’s perspective, tapping the Safari extension toolbar button is the action that initiates the workflow. Is there any supported way for that user-initiated extension action to launch or wake the containing iOS app so it can process pending App Group requests? Or should Safari Web Extensions on iOS be designed only to persist work and then ask the user to manually open the containing app? If manual app launch is the intended model, it would be helpful for the documentation to state this explicitly. The current tripartite model strongly suggests that the JavaScript extension, native handler, and containing app can collaborate as parts of one workflow, but on iOS the containing app appears to be available only out-of-band unless already running.
Replies
0
Boosts
0
Views
165
Activity
1w
Xcode 27: spike in "Class X is implemented in both" warnings
Anyone else seeing a lot more "Class X is implemented in both ..." warnings on Xcode 27 than on Xcode 26? Same source, same flags, the count goes from a handful to a couple thousand, and some now correlate with real crashes (cast failures, missing protocol conformances) instead of the usual harmless first-wins behavior. Is this a known change in Swift 6.4 / Xcode 27? Is there a new flag I should be passing? Any suggestions welcome.
Replies
3
Boosts
0
Views
229
Activity
1w
Xcode 26.4 and 26.3: Swift compiler crashes during archive with iOS 17 deployment target
I submitted this to Feedback Assistant as FB22331090 and wanted to share a minimal reproducible example here in case others are seeing the same issue. Environment: Xcode 26.4 or Xcode 26.3 Apple Swift version 6.3 (swiftlang-6.3.0.123.5 clang-2100.0.123.102) Effective Swift language version 5.10 Deployment target: iOS 17.0 The sample app builds successfully for normal development use, but archive fails. The crash happens during optimization in EarlyPerfInliner while compiling the synthesized deinit of a nested generic Coordinator class. The coordinator stores a UIHostingController. Minimal reproducer: import SwiftUI struct ReproView<Content: View>: UIViewRepresentable { let content: Content func makeUIView(context: Context) -> UIView { context.coordinator.host.view } func updateUIView(_ uiView: UIView, context: Context) { context.coordinator.host.rootView = content } func makeCoordinator() -> Coordinator { Coordinator(content: content) } final class Coordinator { let host: UIHostingController<Content> init(content: Content) { host = UIHostingController(rootView: content) } } } Used from ContentView like this: ReproView(content: Text("Hello")) Steps: Create a new SwiftUI iOS app. Set deployment target to iOS 17.0. Add the code above. Archive. Expected result: Archive succeeds, or the compiler emits a normal diagnostic. Actual result: The Swift compiler crashes and prints: "Please submit a bug report" "While running pass ... SILFunctionTransform 'EarlyPerfInliner'" The crash occurs while compiling the synthesized deinit for ReproView.Coordinator. Relevant log lines from my archive log: line 209: Please submit a bug report line 215: While running pass ... EarlyPerfInliner line 216: for 'deinit' at ReproView.swift:19:17 One more detail: The same sample archived successfully when the deployment target was higher. Lowering the deployment target to iOS 17.0 made the archive crash reproducible. This may be related to another forum thread about release-only compiler crashes, but the reproducer here is different: this one uses a generic UIViewRepresentable with a nested Coordinator storing UIHostingController.
Replies
3
Boosts
1
Views
391
Activity
1w