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
1.2k
Oct ’25
SwiftUI WebView: Is action.target == nil a Reliable Way to Handle New Window Requests?
In WKWebView, there is the WKUIDelegate method: func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {} This delegate method provides a callback when a new window (for example, target="_blank") is requested in the web view. However, in native SwiftUI (iOS 26), WebView / WebPage APIs do not provide an equivalent delegate method to handle new window requests. As a workaround, I am using the following method: public func decidePolicy(for action: WebPage.NavigationAction, preferences: inout WebPage.NavigationPreferences) async -> WKNavigationActionPolicy {} In this method, when action.target == nil, I treat it as a new window request. My question: Is relying on action.target == nil in decidePolicy a reliable and future-safe way to detect new window requests in SwiftUI’s WebView, or is there a better or more recommended approach for handling target="_blank" / new window navigation in the SwiftUI WebView APIs? Code: public func decidePolicy(for action: WebPage.NavigationAction, preferences: inout WebPage.NavigationPreferences) async -> WKNavigationActionPolicy { guard let webPage = webPage else { return .cancel } // Handle case where target frame is nil (e.g., target="_blank" or window.open) // This indicates a new window request if action.target == nil { print("Target frame is nil - new window requested") // WORKAROUND: Until iOS 26 WebPage UI protocol is available, we handle new windows here // Try to create a new WebPage through UI plugins if handleCreateWebPage(for: webPage, navigationAction: action) != nil { // Note: The new WebPage has been created and published to the view return .allow } } return .allow }
0
0
59
21h
Inserting an NSView (Cocoa) in NSWindowController Views hierarchy
I have an NSWindowController with several IBOutlets created in storyboard. I want to add an NSView and fill it with some color. I need to place it at a specific position in views hierarchy. I have tried 2 ways, no one succeeds. First. include a custom view in storyboard connect to an IBOutlet in an init of controller, set the layer for the view Result: crash Second build programmatically Result: I do not find where to put this code in the controller code That's basic Cocoa, but way more painful than iOS.
3
0
152
1d
Where did I screw up trying concurrency?
I tried making a concurrency-safe data queue. It was going well, until memory check tests crashed. It's part of an unadvertised git project. Its location is: https://github.com/CTMacUser/SynchronizedQueue/commit/84a476e8f719506cbd4cc6ef513313e4e489cae3 It's the blocked-off method "`memorySafetyReferenceTypes'" in "SynchronizedQueueTests.swift." Note that the file and its tests were originally AI slop.
1
0
59
2d
List rows partially obscured by navigation bar briefly render fully opaque when switching tabs (iOS 26)
Overview In iOS 26, a List embedded in a NavigationStack inside a TabView exhibits a visual glitch when switching tabs. When the list is scrolled such that some rows are partially obscured by the navigation bar, the system correctly applies a fade/opacity effect to those rows. However, if the user switches to another tab while rows are in this partially obscured (faded) state, those rows briefly flash at full opacity during the tab transition before disappearing. This flash is visually distracting and appears to be inconsistent with the intended scroll-edge opacity behavior. The issue occurs only for rows partially obscured by the navigation bar. Rows partially obscured by the tab bar do not exhibit this flashing behavior. Steps to Reproduce: Run the attached minimal reproduction on iOS 26. Open the first tab. Scroll the list so that some rows are partially hidden behind the navigation bar (showing the native faded appearance). While rows are in this partially faded state, switch to the second tab. Observe that the faded rows briefly render fully opaque during the tab switch. Expected Behavior: Rows that are partially obscured by the navigation bar should maintain consistent opacity behavior during tab transitions, without flashing to full opacity. import SwiftUI @main struct NavBarReproApp: App { /// Minimal repro for iOS 26: /// - TabView with two tabs /// - First tab: NavigationStack + List /// - Scroll so some rows are partially behind the nav bar (faded) /// - Switch tabs: those partially-faded rows briefly flash fully opaque. Partially faded rows under the tab bar do not flash private let items = Array(0..<200).map { "Row \($0)" } var body: some Scene { WindowGroup { TabView { NavigationStack { List { ForEach(items, id: \.self) { item in Text(item) } } .navigationTitle("One") .navigationBarTitleDisplayMode(.inline) } .tabItem { Label("One", systemImage: "1.circle") } NavigationStack { Text("Second tab") .navigationTitle("Two") .navigationBarTitleDisplayMode(.inline) } .tabItem { Label("Two", systemImage: "2.circle") } } } } }
6
0
88
2d
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
0
0
51
2d
[iOS 26.2] Crash due to WKScriptMessageHandler delegate
The crash is specific to iOS 26.2 prior versions working fine. WKScriptMessageHandler delegate func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) Name attribute is accessible but WKScriptMessage body attribute causes crash The object seems to be not accessible(not in memory) self.webkit.configuration.userContentController.add(self, name: "sampleHandler") self.webkit.load(request) func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { print(message.name) // works print(message.body) // crashes }
5
1
1.4k
2d
Trailing closure passed to parameter of type 'Int' that does not accept a closure
I have TabView in ContentView and I want to add TabView for OnboardingView in OtherView, every things work, but it is throw error for TabView in OtherView like "Trailing closure passed to parameter of type 'Int' that does not accept a closure" I do not know why? Any idea? ContentView: struct TabView : View {       var body: some View{           VStack(spacing: 0){ ....... } OtherView:    VStack {     TabView {       ForEach(onboardingData) { onboardingItem in          OnboardingCard(onboardingItem: onboardingItem)       }   }   .tabViewStyle(PageTabViewStyle(indexDisplayMode: .automatic))   .indexViewStyle(PageIndexViewStyle (backgroundDisplayMode:   .always))   .foregroundColor(.white) }
9
1
6.6k
2d
Content Filter Permission Prompt Not Appearing in TestFlight
I added a Content Filter to my app, and when running it in Xcode (Debug/Release), I get the expected permission prompt: "Would like to filter network content (Allow / Don't Allow)". However, when I install the app via TestFlight, this prompt doesn’t appear at all, and the feature doesn’t work. Is there a special configuration required for TestFlight? Has anyone encountered this issue before? Thanks!
18
1
737
3d
Setting the highlight colour of a selected cell in NSTableView
That's a question for Mac app (Cocoa). I want to change the standard highlighting. I thought to use tableView.selectionHighlightStyle. But there are only 2 values: .none and .regular. Cannot find how to define a custom one. So I tried a workaround: set tableView.selectionHighlightStyle to .none func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { tableView.selectionHighlightStyle = .none keep track of previousSelection Then, in tableViewSelectionDidChange reset for previousSelection func tableViewSelectionDidChange(_ notification: Notification) { } if previousSelection >= 0 { let cellView = theTableView.rowView(atRow: previousSelection, makeIfNecessary: false) cellView?.layer?.backgroundColor = .clear } set for the selection to a custom color let cellView = theTableView.rowView(atRow: row, makeIfNecessary: false) cellView?.layer?.backgroundColor = CGColor(red: 0, green: 0, blue: 1, alpha: 0.4) previousSelection = row Result is disappointing : Even though tableView.selectionHighlightStyle is set to .none, it does overlays the cellView?.layer Is there a way to directly change the color for selection ?
4
0
112
3d
Announcing the Swift Student Challenge 2026
Announcing the Swift Student Challenge 2026 Every year, Apple’s Swift Student Challenge celebrates the creativity and ingenuity of student developers from around the world, inviting them to use Swift and Xcode to solve real-world problems in their own communities and beyond. Learn more → https://developer.apple.com/swift-student-challenge/ Submissions for the 2026 challenge will open February 6 for three weeks, and students can prepare with new Develop in Swift tutorials and Meet with Apple code-along sessions. The Apple Developer team is here is to help you along the way - from idea to app, post your questions at any stage of your development here in this forum board or be sure to add the Swift Student Challenge tag to your technology-specific forum question. Your designs. Your apps. Your moment.
13
3
1.7k
4d
ManipulationComponent Not Translating using indirect input
When using the new RealityKit Manipulation Component on Entities, indirect input will never translate the entity - no matter what settings are applied. Direct manipulation works as expected for both translation and rotation. Is this intended behaviour? This is different from how indirect manipulation works on Model3D. How else can we get translation from this component? visionOS 26 Beta 2 Build from macOS 26 Beta 2 and Xcode 26 Beta 2 Attached is replicable sample code, I have tried this in other projects with the same results. var body: some View { RealityView { content in // Add the initial RealityKit content if let immersiveContentEntity = try? await Entity(named: "MovieFilmReel", in: reelRCPBundle) { ManipulationComponent.configureEntity(immersiveContentEntity, allowedInputTypes: .all, collisionShapes: [ShapeResource.generateBox(width: 0.2, height: 0.2, depth: 0.2)]) immersiveContentEntity.position.y = 1 immersiveContentEntity.position.z = -0.5 var mc = ManipulationComponent() mc.releaseBehavior = .stay immersiveContentEntity.components.set(mc) content.add(immersiveContentEntity) } } }
12
4
1.2k
4d
Errors with PerfPowerTelemetryClientRegistrationService and PPSClientDonation when running iOS application in Xcode
I've suddenly started seeing hundreds of the same block of four error messages (see attached image) when running my app on my iOS device through Xcode. I've tried Cleaning the Build folder, but I keep seeing these messages in the console but can't find anything about them. Phone is running iOS 26.1. Xcode is at 16.4. Mac is on Sequoia 15.5. The app is primarily a MapKit SwiftUI based application. Messages below: Connection error: Error Domain=NSCocoaErrorDomain Code=4099 "The connection to service named com.apple.PerfPowerTelemetryClientRegistrationService was invalidated: Connection init failed at lookup with error 159 - Sandbox restriction." UserInfo={NSDebugDescription=The connection to service named com.apple.PerfPowerTelemetryClientRegistrationService was invalidated: Connection init failed at lookup with error 159 - Sandbox restriction.} (+[PPSClientDonation isRegisteredSubsystem:category:]) Permission denied: Maps / SpringfieldUsage (+[PPSClientDonation sendEventWithIdentifier:payload:]) Invalid inputs: payload={ isSPR = 0; } CAMetalLayer ignoring invalid setDrawableSize width=0.000000 height=0.000000 I'm also seeing the following error messages: CoreUI: CUIThemeStore: No theme registered with id=0
6
3
275
4d
Can we decode twice in the same session with unarchiver?
In a class, I call the following (edited to simplify, but it matches the real case). If I do this: func getData() -> someClass? { _ = someURL.startAccessingSecurityScopedResource() if let data = NSData(contentsOf: someURL as URL) { do { let unarchiver = try NSKeyedUnarchiver(forReadingFrom: data as Data) print((unarchiver.decodeObject(of: [NSArray.self, someClass.self /* and few others*/], forKey: oneKey) as? someClass)?.aProperty) if let result = unarchiver.decodeObject(of: [NSArray.self, someClass.self /* same other types*/], forKey: oneKey) as? someClass { unarchiver.finishDecoding() print("unarchived success") return result } else { unarchiver.finishDecoding() print("unarchiving failed") return someClass() } } catch { return nil } } I get a failure on log : unarchiving failed But if I comment out the print(unarchiver.decodeObject) - line 8, it works and I get unarchived success // print((unarchiver.decodeObject(of: [NSArray.self, someClass.self /* and few others*/], forKey: oneKey) as? someClass)?.aProperty) However, when I do exactly the same for another class (I've compared line by line to be sure), it works even with the print statement. What could be happening here ?
3
0
91
4d
AVAssetWriterInput.PixelBufferReceiver.append hangs indefinitely (suspends and never resumes)
I’ve been struggling with a very frustrating issue using the new iOS 26 Swift Concurrency APIs for video processing. My pipeline reads frames using AVAssetReader, processes them via CIContext (Lanczos upscale), and then appends the result to an AVAssetWriter using the new PixelBufferReceiver. The Problem: The execution randomly stops at the ]await append(...)] call. The task suspends and never resumes. It is completely unpredictable: It might hang on the very first run, or it might work fine for 4-5 runs and then hang on the next one. It is independent of video duration: It happens with 5-second clips just as often as with long videos. No feedback from the system: There is no crash, no error thrown, and CPU usage drops to zero. The thread just stays in the suspended state indefinitely. If I manually cancel the operation and restart the VideoEngine, it usually starts working again for a few more attempts, which makes me suspect some internal resource exhaustion or a deadlock between the GPU context and the writer's input. The Code: Here is a simplified version of my processing loop: private func proccessVideoPipeline( readerOutputProvider: AVAssetReaderOutput.Provider<CMReadySampleBuffer<CMSampleBuffer.DynamicContent>>, pixelBufferReceiver: AVAssetWriterInput.PixelBufferReceiver, nominalFrameRate: Float, targetSize: CGSize ) async throws { while !Task.isCancelled, let payload = try await readerOutputProvider.next() { let sampleBufferInfo: (imageBuffer: CVPixelBuffer?, presentationTimeStamp: CMTime) = payload.withUnsafeSampleBuffer { sampleBuffer in return (sampleBuffer.imageBuffer, sampleBuffer.presentationTimeStamp) } guard let currentPixelBuffer = sampleBufferInfo.imageBuffer else { throw AsyncFrameProcessorError.missingImageBuffer } guard let pixelBufferPool = pixelBufferReceiver.pixelBufferPool else { throw NSError(domain: "PixelBufferPool", code: -1, userInfo: [NSLocalizedDescriptionKey: "No pixel buffer pool available"]) } let newPixelBuffer = try pixelBufferPool.makeMutablePixelBuffer() let newCVPixelBuffer = newPixelBuffer.withUnsafeBuffer({ $0 }) try upscale(currentPixelBuffer, outputPixelBuffer: newCVPixelBuffer, targetSize: targetSize ) let presentationTime = sampleBufferInfo.presentationTimeStamp try await pixelBufferReceiver.append(.init(unsafeBuffer: newCVPixelBuffer), with: presentationTime) } } Does anyone know how to fix it?
0
0
84
5d
Simulator is not working.
Hi, I am a UI designer and a total newbie with coding, so I have been using AI in Xcode to do all my coding for my personal project. Everything was working fine until this morning, when I tried to run my app in the simulator (I didn't even change any code from the last time I ran the simulator) and now the simulator is crashing and freezing and I have been trying to fix it with the AI recommendations, but it seems way too complicated for me to handle even with AI's help. I feel like I need to talk to an expert and guide me out of this hole. Please help. Thank you!
3
0
306
5d
Array of Bool require NSNumber.self in NSKeyedArchiver decoding list of types
I decode an object with NSKeyedArchiver (SecureCoding): typealias BoolArray = Array<Array<Bool>> let val = decoder.decodeObject(of: NSArray.self, forKey: someKey) as? BoolArray I get the following log: *** -[NSKeyedUnarchiver validateAllowedClass:forKey:] allowed unarchiving safe plist type ''NSNumber' (0x204cdbeb8) [/System/Library/Frameworks/Foundation.framework]' for key 'NS.objects', even though it was not explicitly included in the client allowed classes set: '{( "'NSArray' (0x204cd5598) [/System/Library/Frameworks/CoreFoundation.framework]" )}'. This will be disallowed in the future. I changed by adding NSNumber.self in the list : let val = decoder.decodeObject(of: [NSArray.self, NSNumber.self], forKey: someKey) as? BoolArray No more warning in log. Is there a reason for this ?
3
0
87
1w
How to solve this NSKeyedArchiver warning
I get several warnings in log: *** -[NSKeyedUnarchiver validateAllowedClass:forKey:] allowed unarchiving safe plist type ''NSNumber' (0x204cdbeb8) [/System/Library/Frameworks/Foundation.framework]' for key 'NS.objects', even though it was not explicitly included in the client allowed classes set: '{( "'NSArray' (0x204cd5598) [/System/Library/Frameworks/CoreFoundation.framework]" )}'. This will be disallowed in the future. I am not sure how to understand it: I have removed every NSNumber.self in the allowed lists for decode. To no avail, still get the avalanche of warnings. What is the key NS.objects about ? What may allowed classes set: '{( "'NSArray' be referring to ? An inclusion of NSArray.self in a list for decode ? The type of a property in a class ?
4
0
252
1w
How to call decoder with the right types ?
I have defined a class : class Item: NSObject, NSSecureCoding { var name : String = "" var color : ColorTag = .black // defined as enum ColorTag: Int var value : Int = 0 static var supportsSecureCoding: Bool { return true } Its decoder includes the following print statement to start: required init(coder decoder: NSCoder) { print(#function, "item should not be nil", decoder.decodeObject(of: Item.self, forKey: someKey))   Another class uses it: class AllItems: NSObject, NSSecureCoding { var allItems : [Item]? static var supportsSecureCoding: Bool { return true } and decodes as follows required init(coder decoder: NSCoder) { super.init() // Not sure it is necessary allItems = decoder.decodeObject(of: NSArray.self, forKey: mykey) as? [Item] print(#function, allItems) // <<-- get nil } I note: decoder returns nil at line 5 I have tried to change to decoder.decodeObject(of: [NSArray.self, NSString.self, NSColor.self, NSNumber.self], forKey: mykey)) Still get nil And, decoder of class Item is not called (no print in the log) What am I missing ?
1
0
61
1w
USSD calls with * and # dont work iOS
I have an application that needs to make a USSD call, but on some devices the * and # don't work on the dialer, on others it does. if let phoneNumber = ussdNumberTextfield.text { let encoded = "telprompt:\(phoneNumber)".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)! if let url = URL(string: encoded) { if application.canOpenURL(url){ DispatchQueue.main.async { self.application.open(url, options: [:]) { success in } } } } }
5
0
1.3k
1w
CarPlay on iOS 14 and iOS 15
My app developed with the new Xcode 26 doesn't appear on CarPlay when running on iOS 14–15 devices. My developer has obtained the com.apple.developer.carplay-driving-task permission, but iOS 16+ devices allow my app to display on CarPlay. Can anyone help resolve this issue? Is it because the carplay-driving-task permission is only available for iOS 16+ devices? If I want compatibility with iOS 14–15 devices, do I need to apply to Apple for the carplay-audio permission to use it? Has anyone encountered a similar issue? Thanks!
1
0
81
1w