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
963
Oct ’25
JavaScript/Swift Interoperability
I think that it would be helpful to have better interoperability between Swift and JavaScript. There are a lot of useful packages on NPM that don't have equivalents for Swift. It would be helpful if Apple provided easier ways to use NPM packages in a Swift project. Currently, the JavaScriptCore framework is missing many standard things used in many packages, like the fetch API. It would be helpful to be able to run sandboxed JavaScript code inside of a Swift app but allow access to specific domains, folders, etc., using a permissions system similar to Deno.
2
0
250
2h
Persisting User Settings with SwiftData
I was wondering what the recommended way is to persist user settings with SwiftData? It seems the SwiftData API is focused around querying for multiple objects, but what if you just want one UserSettings object that is persisted across devices say for example to store the user's age or sorting preferences. Do we just create one object and then query for it or is there a better way of doing this? Right now I am just creating: import SwiftData @Model final class UserSettings { var age: Int = 0 var sortAtoZ: Bool = true init(age: Int = 0, sortAtoZ: Bool = true) { self.age = age self.sortAtoZ = sortAtoZ } } In my view I am doing as follows: import SwiftUI import SwiftData struct SettingsView: View { @Environment(\.modelContext) var context @Query var settings: [UserSettings] var body: some View { ForEach(settings) { setting in let bSetting = Bindable(setting) Toggle("Sort A-Z", isOn: bSetting.sortAtoZ) TextField("Age", value: bSetting.age, format: .number) } .onAppear { if settings.isEmpty { context.insert(UserSettings(age: 0, sortAtoZ: true)) } } } } Unfortunately, there are two issues with this approach: I am having to fetch multiple items when I only ever want one. Sometimes when running on a new device it will create a second UserSettings while it is waiting for the original one to sync from CloudKit. AppStorage is not an option here as I am looking to persist for the user across devices and use CloudKit syncing.
2
0
89
11h
vDSP.DiscreteFourierTransform failed to initialize with 5 * 5 * 2^n count
I am implementing the FFT using vDSP.DiscreteFourierTransform. According to the official documentation, the count parameter has requirements as outlined below: /// The `count` parameter must be: /// * For split-complex real-to-complex: `2ⁿ` or `f * 2ⁿ`, where `f` is `3`, `5`, or `15` and `n >= 4`. /// * For split-complex complex-to-complex: `2ⁿ` or `f * 2ⁿ`, where `f` is `3`, `5`, or `15` and `n >= 3`. /// * For interleaved: `f * 2ⁿ`, where `f` is `2`, `3`, `5`, `3x3`, `3x5`, or `5x5`, and `n>=2`. Despite adhering to these specifications in theory, my attempt to initialize an interleaved DFT with count = 2 * 2 * 5 * 5 (equivalent to 5×5 × 2²) resulted in a failure. Below is the code snippet I used for the initialization: do { let dft = try vDSP.DiscreteFourierTransform( previous: nil, count: 2 * 2 * 5 * 5, direction: .forward, transformType: .complexReal, ofType: DSPComplex.self ) print(dft) } catch { print("DFT init failed:", error) } Could somebody more knowledgeable with these APIs have a look? Thanks!
0
0
46
13h
Push Notifications Error
Hi, I'm experiencing an issue with my app. I use Firebase as my server, and it is great. Still, there is one issue: when I send push notifications from my app to users, the users will get the notification if the app is open, but not when it is closed. I have tried many solutions to fix it, even asking AI, but the issue is still there. I would be happy to give you access to Firebase and the Xcode workspace, as I have no clue how to fix it.
0
0
10
1d
Xcode 26 swiftmodules are incompatible with Xcode 16
I am developing a binary SDK for consumption by others. When we updated to Xcode 26, any builds which are generated cannot be consumed by Xcode 16. The specifics lie in the optionals. The following Swift code generate a .swiftmodule func affectedApi() -> Int? { return 1 } In Xcode 16 it generated the following .swiftmodule in the framework. public func affectedIntApi() -> Swift.Int? In Xcode 26 it adds an "if" statement. #if compiler(>=5.3) && $NonescapableTypes public func affectedIntApi() -> Swift.Int? #endif That if statement prevents Xcode16 from seeing the API, and it causes compile failures. This happens regardless of which Swift version is used, and it only affects functions which use Optionals. Is there a way to prevent the compiler from wrapping the API in that statement?
2
0
55
3d
App rejected for using non-public API __SwiftValue in Runner – Swift runtime false positive?
Hello, Our iOS app (Flutter + Swift) was rejected under Guideline 2.5.1 with the following message: The app uses or references the following non-public or deprecated APIs: Runner Classes: __SwiftValue From our investigation, __SwiftValue appears to be an internal Swift runtime class automatically generated by the Swift compiler for Swift–Objective-C bridging. It is not imported, referenced, or used directly in our source code. We verified that: The symbol exists only in the compiled Runner binary It is not referenced by any third-party framework explicitly It appears in standard Swift runtime behavior We previously removed a legitimate private API (PGHostedWindow) from a dependency and resubmitted, after which this new rejection appeared. Questions: Is __SwiftValue considered a private API usage by App Review, or is this a false positive? Are there recommended build settings or mitigations to prevent this symbol from being flagged? Should this be escalated for manual review? Any guidance from Apple engineers or developers who encountered similar rejections would be greatly appreciated. Thank you.
4
0
340
4d
App rejection because of __SwiftValue
Hi, Our Flutter + Swift iOS app was rejected under Guideline 2.5.1 citing usage of a non-public API: Runner Classes: __SwiftValue From our analysis, __SwiftValue appears to be an internal Swift runtime type automatically generated by the Swift compiler for Swift–Objective-C bridging. It is not referenced in our source code or by any third-party frameworks and only appears in the compiled Runner binary. Has anyone encountered this rejection before? Is __SwiftValue considered a private API by App Review, or is this a known false positive? Are there any recommended build settings or mitigations to avoid this flag?
0
0
42
4d
Need Inputs on Which Extension to Use
Hi all, I have a working macOS (Intel) system extension app that currently uses only a Content Filter (NEFilterDataProvider). I need to capture/log HTTP and HTTPS traffic in plain text, and I understand NETransparentProxyProvider is the right extension type for that. For HTTPS I will need TLS inspection / a MITM proxy — I’m new to that and unsure how complex it will be. For DNS data (in plain text), can I use the same extension, or do I need a separate extension type such as NEPacketTunnelProvider, NEFilterPacketProvider, or NEDNSProxyProvider? Current architecture: Two Xcode targets: MainApp and a SystemExtension target. The SystemExtension target contains multiple network extension types. MainApp ↔ SystemExtension communicate via a bidirectional NSXPC connection. I can already enable two extensions (Content Filter and TransparentProxy). With the NETransparentProxy, I still need to implement HTTPS capture. Questions I’d appreciate help with: Can NETransparentProxy capture the DNS fields I need (dns_hostname, dns_query_type, dns_response_code, dns_answer_number, etc.), or do I need an additional extension type to capture DNS in plain text? If a separate extension is required, is it possible or problematic to include that extension type (Packet Tunnel / DNS Proxy / etc.) in the same SystemExtension Xcode target as the TransparentProxy? Any recommended resources or guidance on TLS inspection / MITM proxy setup for capturing HTTPS logs? There are multiple DNS transport types — am I correct that capturing DNS over UDP (port 53) is not necessarily sufficient? Which DNS types should I plan to handle? I’ve read that TransparentProxy and other extension types (e.g., Packet Tunnel) cannot coexist in the same Xcode target. Is that true? Best approach for delivering logs from multiple extensions to the main app (is it feasible)? Or what’s the best way to capture logs so an external/independent process (or C/C++ daemon) can consume them? Required data to capture (not limited to): All HTTP/HTTPS (request, body, URL, response, etc.) DNS fields: dns_hostname, dns_query_type, dns_response_code, dns_answer_number, and other DNS data — all in plain text. I’ve read various resources but remain unclear which extension(s) to use and whether multiple extension types can be combined in one Xcode target. Please ask if you need more details. Thank you.
5
0
247
5d
Why does NSEvent.addGlobalMonitorForEvents still work in a Sandboxed macOS app
I am building a macOS utility using SwiftUI and Swift that records and displays keyboard shortcuts (like Cmd+C, Cmd+V) in the UI. To achieve this, I am using NSEvent.addGlobalMonitorForEvents(matching: [.keyDown]). I am aware that global monitoring usually requires the app to be non-sandboxed. However, I am seeing some behavior I don't quite understand during development: I started with a fresh SwiftUI project and disabled the App Sandbox. I requested Accessibility permissions using AXIsProcessTrustedWithOptions, manually enabled it in System Settings, and the global monitor worked perfectly. I then re-enabled the App Sandbox in "Signing & Capabilities." To my surprise, the app still records global events from other applications, even though the Sandbox is now active. Is this expected behavior? Does macOS "remember" the trust because the Bundle ID was previously authorized while non-sandboxed, or is there a specific reason a Sandboxed app can still use addGlobalMonitor if the user has manually granted Accessibility access? My app's core feature is displaying these shortcuts for the user's own reference (productivity tracking). If the user is the one explicitly granting permission via the Accessibility privacy pane, will Apple still reject the app for using global event monitors within a Sandboxed environment? Code snippet of my monitor: // This is still firing even after re-enabling Sandbox eventMonitor = NSEvent.addGlobalMonitorForEvents(matching: [.keyDown]) { event in print("Captured: \(event.charactersIgnoringModifiers ?? "")") } I've tried cleaning the build folder and restarting the app, removing the app from accessibility permission, but the events keep coming through. I want to make sure I'm not relying on a "development glitch" before I commit to the App Store path. Here is the full code anyone can use to try this :- import SwiftUI import Cocoa import Combine struct ShortcutEvent: Identifiable { let id = UUID() let displayString: String let timestamp: Date } class KeyboardManager: ObservableObject { @Published var isCapturing = false @Published var capturedShortcuts: [ShortcutEvent] = [] private var eventMonitor: Any? // 1. Check & Request Permissions func checkAccessibilityPermissions() -> Bool { let options: NSDictionary = [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] let accessEnabled = AXIsProcessTrustedWithOptions(options) return accessEnabled } // 2. Start Capture func startCapture() { guard checkAccessibilityPermissions() else { print("Permission denied") return } isCapturing = true let mask: NSEvent.EventTypeMask = [.keyDown, .keyUp] eventMonitor = NSEvent.addGlobalMonitorForEvents(matching: mask) { [weak self] event in self?.processEvent(event) } } // 3. Stop Capture func stopCapture() { if let monitor = eventMonitor { NSEvent.removeMonitor(monitor) eventMonitor = nil } isCapturing = false } private func processEvent(_ event: NSEvent) { // Only log keyDown to avoid double-counting the UI display guard event.type == .keyDown else { return } var modifiers: [String] = [] var symbols: [String] = [] // Map symbols for the UI if event.modifierFlags.contains(.command) { modifiers.append("command") symbols.append("⌘") } if event.modifierFlags.contains(.shift) { modifiers.append("shift") symbols.append("⇧") } if event.modifierFlags.contains(.option) { modifiers.append("option") symbols.append("⌥") } if event.modifierFlags.contains(.control) { modifiers.append("control") symbols.append("⌃") } let key = event.charactersIgnoringModifiers?.uppercased() ?? "" // Only display if a modifier is active (to capture "shortcuts" vs regular typing) if !symbols.isEmpty && !key.isEmpty { let shortcutString = "\(symbols.joined(separator: " ")) + \(key)" DispatchQueue.main.async { // Insert at the top so the newest shortcut is visible self.capturedShortcuts.insert(ShortcutEvent(displayString: shortcutString, timestamp: Date()), at: 0) } } } } PS :- I just did another test by creating a fresh new project with the default App Sandbox enabled, and tried and there also it worked!! Can I consider this a go to for MacOs app store than?
1
0
411
5d
Parameter Errors - procedural vs. optional
So I’m writing a program, as a developer would - ‘with Xcode.’ Code produced an error. The key values were swapped. The parameters suggested were ‘optional parameters variables.’ “var name: TYPE? = (default)” var name0: TYPE ============================= name0 = “super cool” ‘Name is not yet declared at this point provided with x - incorrect argument replace ExampleStruct(name:”supercool”) should be x - incorrect argument replace ExampleStruct(name0:”supercool”) ============================= In swift, there is a procedural prioritization within the constructor calling process. Application calls constructor. Constructor provides constructor signature. Signature requires parameters & throws an error if the params are not in appropriate order. - “got it compiler; thank you, very much” Typically, when this occurs, defaults will be suggested. Often the variable type. Ie String, Bool. such as: StructName(param1:Int64, param2:Bool) (Recently, I have seen a decline in @Apple’s performance in many vectors.) As stated before, the key value pairs were out of sequence. The optionals were suggested instead of the required parameters. This leads me to believe that there is an order of operations in the calling procedure that is being mismanaged. I.e. regular expression, matching with optional. This confuses these with [forced, required] parameters, and the mismanagement of ‘key: value’ pairs. this is a superficial prognosis and would like to know if anyone has any insight as to why this may occur. Could it be a configuration setting? Is it possibly the network I connected to bumped into something. Etc.. I appreciate any and all feedback. Please take into consideration the Apple developer forum, guidelines before posting comments. #dev_div
2
0
545
5d
Local network request blocked in Safari but working in Chrome
For Local network access, Chrome prompts the user to allow access and adds it to Settings --> Privacy & Security --> Local Network. However, for Safari, no prompt appears. How do I force Safari to authorise these local network access requests if it won't trigger the permission dialogue? Is there a specific WKWebView configuration or Safari-specific header required to satisfy this security check?
1
0
440
5d
How to distinguish which operations in the file provider are during offline period
Currently tested, if the file provider goes offline (referring to calling disconnect) and deletes a file, the system will automatically trigger the deleteItems event after reconnecting (note that only after calling reconnect again will the current deleteItems logic be reached). However, for offline deletion, I would like to pass it directly without operating on the cloud. Can mounting disks determine which operations were performed offline during reboot
2
0
93
6d
Crash in swift::_getWitnessTable when passing UITraitBridgedEnvironmentKey
When using UITraitBridgedEnvironmentKey to pass a trait value to the swift environment, it causes a crash when trying to access the value from the environment. The issue seems to be related to how swift uses the UITraitBridgedEnvironmentKey protocol since the crash occurs in swift::_getWitnessTable () from lazy protocol witness table accessor…. It can occur when calling any function that is generic using the UITraitBridgedEnvironmentKey type. I originally encountered the issue when trying to use a UITraitBridgedEnvironmentKey in SwiftUI, but have been able to reproduce the issue with any function with a similar signature. https://developer.apple.com/documentation/swiftui/environmentvalues/subscript(_:)-9zku Steps to Reproduce Requirements for the issue to occur Project with a minimum iOS version of iOS 16 Build the project with Xcode 26 Run on iOS 18 Add the following code to a project and call foo(key: MyCustomTraitKey.self) from anywhere. @available(iOS 17.0, *) func foo<K>(key: K.Type) where K: UITraitBridgedEnvironmentKey { // Crashes before this is called } @available(iOS 17.0, *) public enum MyCustomTraitKey: UITraitBridgedEnvironmentKey { public static let defaultValue: Bool = false public static func read(from traitCollection: UITraitCollection) -> Bool { false } public static func write(to mutableTraits: inout UIMutableTraits, value: Bool) {} } // The crash will occur when calling this. It can be added to a project anywhere // The sample project calls it from scene(_:willConnectTo:options:) foo(key: MyCustomTraitKey.self) For example, I added it to the SceneDelegate in a UIKit Project class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { if #available(iOS 17, *) { // The following line of code can be placed anywhere in a project, `SceneDelegate` is just a convenient place to put it to reproduce the issue. foo(key: MyCustomTraitKey.self) // ^ CRASH: Thread 1: EXC_BAD_ACCESS (code=1, address=0x10) } } } Actual Behaviour The app crashes with the stack trace showing the place calling foo but before foo is actually called. (ie, a breakpoint or print in foo is never hit) #0 0x000000019595fbc4 in swift::_getWitnessTable () #1 0x0000000104954128 in lazy protocol witness table accessor for type MyCustomTraitKey and conformance MyCustomTraitKey () #2 0x0000000104953bc4 in SceneDelegate.scene(_:willConnectTo:options:) at .../SceneDelegate.swift:20 The app does not crash when run on iOS 17, or 26 or when the minimum ios version is raised to iOS 17 or higher. It also doesn't crash on iOS 16 since it's not calling foo since UITraitBridgedEnvironmentKey was added in iOS 17. Expected behaviour The app should not crash. It should call foo on iOS 17, 18, and 26.
0
0
27
6d
During the process of uploading a large file, I moved it to the trash can. How can I directly interrupt this upload process
I am currently encountering a problem: during the process of uploading a large file, I have moved the file that was not successfully uploaded to the trash can. These two operations have been tested to be serial (triggering the 'create Item' callback first, followed by the 'modify Item' callback), which means that the file must be uploaded before it can be moved to the recycle bin (which can also result in the file being stored in the cloud recycle bin). I want to implement: directly interrupt this upload process and then do not complete the upload. How can I achieve this? Please help me. Thank you
2
0
96
6d
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.
9
3
1.3k
6d
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
0
2
142
1w
evaluateJavaScript callback is significantly slow on macOS 26.2 for iOS App on Mac
Hello, After upgrading to macOS 26.2, I’ve noticed a significant performance regression when calling evaluateJavaScript in an iOS App running on Mac (WKWebView, Swift project). Observed behavior On macOS 26.2, the callback of evaluateJavaScript takes around 3 seconds to return. This happens not only for: evaluateJavaScript("navigator.userAgent") but also for simple or even empty scripts, for example: evaluateJavaScript("") On previous macOS versions, the same calls typically returned in ~200 ms. Additional testing I created a new, empty Objective-C project with a WKWebView and tested the same evaluateJavaScript calls. In the Objective-C project, the callback still returns in ~200 ms, even on macOS 26.2. Question Is this a known issue or regression related to: iOS Apps on Mac, Swift + WKWebView, or behavioral changes in evaluateJavaScript on macOS 26.2? Any information about known issues, internal changes, or recommended workarounds would be greatly appreciated. Thank you. Test Code Swift class ViewController: UIViewController { private var tmpWebView: WKWebView? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. setupUserAgent() } func setupUserAgent() { let t1 = CACurrentMediaTime() tmpWebView = WKWebView(frame: .zero) tmpWebView?.isInspectable = true tmpWebView?.evaluateJavaScript("navigator.userAgent") { [weak self] result, error in let t2 = CACurrentMediaTime() print("[getUserAgent] \(t2 - t1)s") self?.tmpWebView = nil } } } Test Code Objective-C - (void)scene:(UIScene *)scene willConnectToSession:(UISceneSession *)session options:(UISceneConnectionOptions *)connectionOptions { NSTimeInterval startTime = [[NSDate date] timeIntervalSince1970]; WKWebView *webView = [[WKWebView alloc] init]; dispatch_async(dispatch_get_main_queue(), ^{ [webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) { NSTimeInterval endTime = [[NSDate date] timeIntervalSince1970]; NSLog(@"[getUserAgent]: %.2f s", (endTime - startTime)); }]; }); }
1
1
545
1w
Do we still need to comply with SB2420 on Jan 1st for distributing apps in Texas ?
According to this news, we don't need anymore (at least temporarily): https://www.macrumors.com/2025/12/23/texas-app-store-law-blocked/ A Texas federal judge today blocked an App Store age verification law that was set to go into effect on January 1, 2026, which means Apple may not have to support the changes after all. Hope we shall get very rapidly more information from Apple.
1
0
132
2w