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

Posts under Swift tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Unable to see *any* debug statements from the FileProviderExtension spawned from Finder
I am in the process of writing a macOS app using NSFileProviderExtension so that I can map my customer's data in Finder. I am in the process of building it out, I had initially started in Obj-C and then after the advice of folks here (https://developer.apple.com/forums//thread/793272?answerId=849339022&page=1#849752022) I have switched to Swift as the NSReplicatedFileProvider is not available in Obj-C. I have done the main app and also started plugging away with the FileProviderExtension. To verify that I have properly setup, I create a static list of files in the FileProviderExtension enumerate so I can see it work in Finder. I build the app and it works as expected and I see it mounted in Finder and I see the static list of files. But what I don't see is any debug statements in the app, none of those message show up in the logs. I am baffled by this. I check the log stream to see what the process prints out and I know it is logging everything else eg: 2025-07-18 11:32:05.772364-0700 0x19ea3f9 Activity 0x1172100 63622 0 DriveFileProviderExtension: (libsystem_secinit.dylib) AppSandbox 2025-07-18 11:32:05.794609-0700 0x19ea3f9 Activity 0x1172101 63622 0 DriveFileProviderExtension: (libsystem_info.dylib) Retrieve User by ID 2025-07-18 11:32:05.800179-0700 0x19ea3f9 Default 0x0 63622 0 DriveFileProviderExtension: (ExtensionFoundation) [com.apple.extensionkit:default] Extension `/Users/radwar/Library/Developer/Xcode/DerivedData/Drive-fxfhbjutfvumoabnnfmxxstpifha/Build/Products/Debug/Drive.app/Contents/PlugIns/DriveFileProviderExtension.appex/Contents/MacOS/DriveFileProviderExtension` of type: `1` launched. 2025-07-18 11:32:05.801453-0700 0x19ea3f9 Default 0x0 63622 0 DriveFileProviderExtension: (RunningBoardServices) [com.apple.runningboard:connection] Initializing connection 2025-07-18 11:32:05.803083-0700 0x19ea3f9 Default 0x0 63622 0 DriveFileProviderExtension: (RunningBoardServices) [com.apple.runningboard:process] Removing all cached process handles 2025-07-18 11:32:05.803231-0700 0x19ea613 Default 0x0 63622 0 DriveFileProviderExtension: (RunningBoardServices) [com.apple.runningboard:connection] Sending handshake request attempt #1 to server 2025-07-18 11:32:05.803414-0700 0x19ea613 Default 0x0 63622 0 DriveFileProviderExtension: (RunningBoardServices) [com.apple.runningboard:connection] Creating connection to com.apple.runningboard 2025-07-18 11:32:05.803459-0700 0x19ea613 Default 0x0 63622 0 DriveFileProviderExtension: (libxpc.dylib) [com.apple.xpc:connection] [0x12f106e10] activating connection: mach=true listener=false peer=false name=com.apple.runningboard 2025-07-18 11:32:05.805893-0700 0x19ea613 Default 0x0 63622 0 DriveFileProviderExtension: (RunningBoardServices) [com.apple.runningboard:connection] Handshake succeeded 2025-07-18 11:32:05.805955-0700 0x19ea613 Default 0x0 63622 0 DriveFileProviderExtension: (RunningBoardServices) [com.apple.runningboard:connection] Identity resolved as xpcservice<clio.Drive.DriveFileProviderExtension([osservice<com.apple.FileProvider(501)>:990])(501)>{vt hash: 247410607}[uuid:454E32DB-3FB4-4DC6-9C05-F4B2F97333E0]{persona:9EF54117-4998-4D72-83C4-F12587C95FBA} but none of my print lines are being printed. I have code like this sprinkled through the methods: print("🔍 FileProviderExtension INIT - Logger configured") print("🔍 Domain: \(domain.displayName)") None of these show up anywhere. I also do a pure log stream with all system output, and there, too, I don't see anything. What am I missing? With my Obj-C version, all NSLogs used to show up as expected. With Swift, am I missing something?
0
0
36
8h
AsyncStream does not cancel inner Task
AsyncStream { continuation in Task { let response = await getResponse() continuation.yield(response) continuation.finish() } } In this WWDC video https://developer.apple.com/videos/play/wwdc2025/231/ at 8:20 the presenter mentions that if the "Task gets cancelled, the Task inside the function will automatically get cancelled too". The documentation does not mention anything like this. From my own testing on iOS 18.5, this is not true.
2
0
259
1d
App crashes on launch due to missing Swift Concurrency symbol
I'm encountering a crash on app launch. The crash is observed in iOS version 17.6 but not in iOS version 18.5. The only new notable thing I added to this app version was migrate to store kit 2. Below is the error message from Xcode: Referenced from: &lt;DCC68597-D1F6-32AA-8635-FB975BD853FE&gt; /private/var/containers/Bundle/Application/6FB3DDE4-6AD5-4778-AD8A-896F99E744E8/callbreak.app/callbreak Expected in: &lt;A0C8B407-0ABF-3C28-A54C-FE8B1D3FA7AC&gt; /usr/lib/swift/libswift_Concurrency.dylib Symbol not found: _$sScIsE4next9isolation7ElementQzSgScA_pSgYi_tYa7FailureQzYKFTu Referenced from: &lt;DCC68597-D1F6-32AA-8635-FB975BD853FE&gt; /private/var/containers/Bundle/Application/6FB3DDE4-6AD5-4778-AD8A-896F99E744E8/callbreak.app/callbreak Expected in: &lt;A0C8B407-0ABF-3C28-A54C-FE8B1D3FA7AC&gt; /usr/lib/swift/libswift_Concurrency.dylib dyld config: DYLD_LIBRARY_PATH=/usr/lib/system/introspection DYLD_INSERT_LIBRARIES=/usr/lib/libLogRedirect.dylib:/usr/lib/libBacktraceRecording.dylib:/usr/lib/libMainThreadChecker.dylib:/usr/lib/libRPAC.dylib:/System/Library/PrivateFrameworks/GPUToolsCapture.framework/GPUToolsCapture:/usr/lib/libViewDebuggerSupport.dylib``` and Stack Trace: ```* thread #1, stop reason = signal SIGABRT * frame #0: 0x00000001c73716f8 dyld`__abort_with_payload + 8 frame #1: 0x00000001c737ce34 dyld`abort_with_payload_wrapper_internal + 104 frame #2: 0x00000001c737ce68 dyld`abort_with_payload + 16 frame #3: 0x00000001c7309dd4 dyld`dyld4::halt(char const*, dyld4::StructuredError const*) + 304 frame #4: 0x00000001c73176a8 dyld`dyld4::prepare(...) + 4088 frame #5: 0x00000001c733bef4 dyld`start + 1748``` Note: My app is a Godot App and uses objc static libraries. I am using swift with bridging headers for interoperability. This issue wasn't observed until my last version in which the migration to storekit2 was the only notable change.
1
0
45
1d
Dynamically Create Tool Argument Type
According to the Tool documentation, the arguments to the tool are specified as a static struct type T, which is given to tool.call(argument: T) However, if the arguments are not known until runtime, is it possible to still create a Tool object with the proper parameters? Let's say a JSON-style dictionary is passed into the Tool init function to specify T, is this achievable?
1
0
287
2d
View lifecycle in Tabview
In TabView, when I open a view in a Tab, and I switch to another Tab, but the View lifecycle of the view in the old Tab is still not over, and the threads of some functions are still in the background. I want to completely end the View lifecycle of the View in the previously opened tab when switching Tab. How can I do it? Thank you!
0
0
95
3d
Unstable Playlist.Entry.id causes crashes when removing duplicates
When multiple identical songs are added to a playlist, Playlist.Entry.id uses a suffix-based identifier (e.g. songID_0, songID_1, etc.). Removing one entry causes others to shift, changing their .id values. This leads to diffing errors and collection view crashes in SwiftUI or UIKit when entries are updated. Steps to Reproduce: Add the same song to a playlist multiple times. Observe .id.rawValue of entries (e.g. i.SONGID_0, i.SONGID_1). Remove one entry. Fetch playlist again — note the other IDs have shifted. FB18879062
0
0
416
3d
Passing string between Swift and C++
I want to understand what the recommended way is for string interoperability between swift and c++. Below are the 3 ways to achieve it. Approach 2 is not allowed at work due to restrictions with using std libraries. Approach 1: In C++: char arr[] = "C++ String"; void * cppstring = arr; std::cout<<"before:"<<(char*)cppstring<<std::endl;           // C++ String // calling swift function and passing the void buffer to it, so that swift can update the buffer content Module1::SwiftClass:: ReceiveString (cppstring, length);   std::cout<<"after:"<<(char*)cppstring<<std::endl;             // SwiftStr      In Swift: func ReceiveString (pBuffer : UnsafeMutableRawPointer , pSize : UInt ) -> Void { // to convert cpp-str to swift-str: let swiftStr = String (cString: pBuffer.assumingMemoryBound(to: Int8.self)); print("pBuffer content: \(bufferAsString)"); // to modify cpp-str without converting: let swiftstr:String = "SwiftStr"      _ =  swiftstr.withCString { (cString: UnsafePointer<Int8>) in pBuffer.initializeMemory(as: Int8.self, from: cString, count: swiftstr.count+1) } }  Approach 2:  The ‘String’ type returned from a swift function is received as ‘swift::String’ type in cpp. This is implicitly casted to std::string type. The std::string has the method available to convert it to char *. void TWCppClass::StringConversion () {     // GetSwiftString() is a swift call that returns swift::String which can be received in std::string type     std::string stdstr = Module1::SwiftClass::GetSwiftString ();     char * cstr = stdstr.data ();     const char * conststr= stdstr.c_str (); }    Approach 3: The swift::String type that is obtained from a swift function can be received in char * by directly casting the address of the swift::String. We cannot directly receive a swift::String into a char *. void TWCppClass::StringConversion () {    // GetSwiftString() is a swift call that returns swift::String    swift::String swiftstr = Module1::SwiftClass::GetSwiftString ();    // obtaining the address of swift string and casting it into char *    char * cstr = (char*)&swiftstr; }
1
0
302
2d
Load bundle resources in UI Tests
I want to load images from my bundle, which works fine when running the main app. However this does not work when running UI Tests. I read that the test bundle is not the main bundle when running tests. I try loading the bundle via this snippet: let bundle = Bundle(for: Frames_HoerspielUITests.self) This is my test class wrapped these the canImport statements so it can be added to the main app target and used for getting the correct bundle: #if canImport(XCTest) import XCTest final class Frames_HoerspielUITests: XCTestCase { override func setUpWithError() throws { continueAfterFailure = false } override func tearDownWithError() throws { } @MainActor func testExample() throws { let app = XCUIApplication() app.launch() } @MainActor func testLaunchPerformance() throws { measure(metrics: [XCTApplicationLaunchMetric()]) { XCUIApplication().launch() } } } #else final class Frames_HoerspielUITests { } #endif However while this works when running the main app, it still fails in the UI tests. It is a SwiftUI only app. and I can't add the images to the asset catalog because they are referenced from another location. Any ideas? Thank you
1
0
203
2d
How to use protocols to support managing SwiftUI views from different modules ?
In out project, we are creating a modular architecture where each module conform to certain protocol requirements for displaying the UI. For example: public protocol ModuleProviding: Sendable { associatedtype Content: View /// Creates and returns the main entry point view for this module /// - Parameter completion: Optional closure to be called when the flow completes /// - Returns: The main view for this module @MainActor func createView(_ completion: (() -> Void)?) -> Content } This protocol can be implemented by all different modules in the app, and I use a ViewProvider structure to build the UI from the module provided: public struct ViewProvider: Equatable { let id = UUID() let provider: any ModuleProviding let completion: () -> Void public init(provider: any ModuleProviding, completion: @escaping () -> Void) { self.provider = provider self.completion = completion } @MainActor public func layoutUI() -> some View { provider.createView(completion) } This code throws an error: Type 'any View' cannot conform to 'View' To solve this error, there are two ways, one is to wrap it in AnyView, which I don't want to do. The other option is to type check the provider with its concrete type: @ViewBuilder @MainActor private func buildViewForProvider(_ provider: any ModuleProviding, completion: (() -> Void)?) -> some View { switch provider { case let p as LoginProvider: p.createView(completion) case let p as PostAuthViewProvider: p.createView(completion) case let p as OnboardingProvider: p.createView(completion) case let p as RewardsProvider: p.createView(completion) case let p as SplashScreenProvider: p.createView(completion) default: EmptyView() } } This approach worked, but it defeats the purpose of using protocols and it is not scalable anymore. Are there any other approaches I can look at ? Or is this limitation in SwiftUI ?
3
0
86
4d
iOS 26 ScrollView with static background image
I need a layout where I have a ScrollView with some content, and ScrollView has full screen background image. Screen is pushed as detail on stack. When my screen is pushed we display navigation bar. We want a new scrollEdgeEffectStyle .soft style work. But when we scroll the gradient blur effect bellow bars is fixed to top and bottom part of the scroll view background image and is not transparent. However when content underneath navigation bar is darker and navigation bar changes automatically to adapt content underneath the final effect looks as expected doesn't use background image. Expected bahaviour for us is that the effect under the navigation bar would not use background image but would be transparent based on content underneath. This is how it is intialy when user didn't interact with the screen: This is how it looks when user scrolls down: This is how it looks when navigation bar adapts to dark content underneath: Minimal code to reproduce this behaviour: import SwiftUI @main struct SwiftUIByExampleApp: App { var body: some Scene { WindowGroup { ContentView() } } } struct ContentView: View { var body: some View { NavigationStack { ScrollView(.vertical) { VStack(spacing: 0.0) { ForEach(1 ..< 101, id: \.self) { i in HStack { Text("Row \(i)") Spacer() } .frame(height: 50) .background(Color.random) } } } .scrollEdgeEffectStyle(.soft, for: .all) .scrollContentBackground(.hidden) .toolbar { ToolbarItem(placement: .title) { Label("My Awesome App", systemImage: "sparkles") .labelStyle(.titleAndIcon) } } .toolbarRole(.navigationStack) .background( ZStack { Color.white .ignoresSafeArea() Image(.sea) .resizable() .ignoresSafeArea() .scaledToFill() } ) } } } extension Color { static var random: Color { Color( red: .random(in: 0...1), green: .random(in: 0...1), blue: .random(in: 0...1) ) } } We've also tried using ZStack instead of .background modifier but we observed the same results. We want to basically achieve the same effect as showcased here, but with the static background image: https://youtu.be/3MugGCtm26A?si=ALG29NqX1jAMacM5&t=634
0
0
91
4d
sheetPresentationController and iOS 26 Beta
I my App I use the sheetPresentationController to get a sheet that sits on top of the main view (a Map) and that can be slided up and down, similar to the Maps or FindMy Apps. This works great with iOS 18 and older. But under iOS 26 Beta I see issues, especially on the iPad. When the window is small (iPhone or compact size class on iPad), changing the height of the sheet works as expected, the sheet window is attached to the bottom of the screen and I can slide it up and down. But when the App window is wider (regular size class on the iPad), the sheet is shown at the left (as expected), but it is no longer attached to the bottom of the screen, there's a very large (but constant) gap between the bottom of the App window and the bottom of the sheet. I haven't found a way to minimize the gap, the sheet window seems to totally ignore the vertical position and size of the "sourceView" to which the sheet should be attached to (it still evaluates the horizontal position, so I can move the sheet to the right, but the vertical position can't be controlled anymore). The Maps App or FindMy Apps do not show this issue, also iOS 18 and older do not show this issue. Is this normal or can I do something to prevent this? The sheet should always be positioned to the bottom left corner of the App window, Another problem is the window background with a UIGlassContainer effect. In the Apple Maps App the sheet looses its glass effect transparency under iOS 26 when the sheet is fully expanded. The FindMy does not have this issue, here the glass effect/transparency is always present. In my App the background shows the glass effect when the window is not fully expanded when the overall App window is above a certain height (like the Apple Maps App), but when the App window is below a certain height then it is the opposite way: fully expanded it shows the glass effect and at smaller heights it is opaque. Why is this the case? How can I get the behavior of the FindMy App where the sheet window keeps its transparent glass effect in all cases? I do not want to have it changing its appearance depending of the height of the sheet. I can "solve" some of the issues when presenting the "sheet" as popover (via popoverPresentationController) and from within the popoverPresentationController use the adaptiveSheetPresentationController property to get the UISheetPresentationController (instead of directly using the sheetPresentationController property). In small App windows (iPhone or compact size class) it works exactly as when directly using sheetPresentationController. With larger App windows (iPad and regular size class) the sheet will be attached to the bottom of the App window (as expected) and the glass effect is always present. However in this case the detents which define the allowed heights of the sheet window will be always ignored, the window seems to have always the maximum height (minus some safe areas), Even when using the preferredContentSize property to set the size, only the width is respected, but never the height. Is there any way to get this working? Is this supposed to work this way or is this still a beta issue?
0
0
107
5d
iOS 26 Beta 3 `safeAreaInsets`
I noticed that trying to access safeAreaInsets from the active window causes an infinite run loop. This issue appeared after updating to Beta 3. Here’s an example of the code: extension UIDevice { var safeAreaInsets: UIEdgeInsets { guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene, let window = windowScene.windows.first(where: { $0.isKeyWindow }) else { return .zero } return window.safeAreaInsets } } The return doesn’t happen because it ends up in some kind of recursion.
2
0
178
4d
Beginner Question - Local SPM Folder Structure
Hi there, I am working on an iOS mobile app, with a MVVM architecture and created an SPM folders for my DesignSystem, CoreKit, UnityBridge, and VoicePipeline. I added the packages locally, and dragged them into the project. Is working this way recommended? Or not? Should all the SPM folders I listed above be used this way, or should only some? New to this, unsure what is best. I do plan on sharing my code with other devs to work on. I thought this made sense, but if i did it the other way I was unsure how I would share the packages what is a best practice. Thanks so much!
1
0
52
4d
addSubview with bounds not working
I'm using Swift to display some text in the middle of the screen, but I'm doing this programmatically instead of using the layout designer. So I'm starting with my version of a UILabel: class GenericLabel: UILabel I'm then creating one of these objects: let label = GenericLabel(frame: CGRect.zero) label.processResponse(componentDictionary ) view.addSubview(label) The processResponse function will set the text value, the font, fontsize, and set the bounds for where the text should be displayed on the screen. Currently I'm just wanting to position the text in the centre of the screen. During this process I send some messages to the console, like my calculation of the width and height and the bounds value. The console includes this: GenericLabel: default = centrex and centrey Utils:setSize: parent view bounds = (0.0, 0.0, 402.0, 874.0) Utils:setSize: obj size = (85.33333333333333, 20.333333333333332) Utils.setSize: centrey myframe.origin.y = 426.8333333333333 Utils.setSize: centrex myframe.origin.x = 158.33333333333334 Utils:setSize: myframe is now set to = (158.33333333333334, 426.8333333333333, 85.33333333333333, 20.333333333333332) self.frame set to (158.33333333333334, 426.8333333333333, 85.33333333333333, 20.333333333333332) Finally I set this frame to my GenericLabel self.frame = Utils.setSize(["centrex":0, "centrey":0], for: self) // You can see this message in the console above print("self.frame set to \(self.frame)") Unfortunately the text appears at (0,0) as in this screenshot. Why is the frame not working? Is there some setting overriding the frame?
2
0
85
5d
Using SwiftUI .sheet: ScrollView rendering issue when used inside NavigationStack
I am encounter an issue with the height of a ScrollView not rendering properly during the transition of a sheet from closed to open. This results in a gap between the bottom edge of the ScrollView and the bottom edge of the sheet during the animation. I am getting this issue when trying to use the ScrollView inside a NavigationStack and when using a PresentationDetent other than .large. The code snippet below, for example, suffers from the issue. ScrollView { Button("Reveal sheet") { isPresented = true } } .frame(maxWidth: .infinity) .background(.yellow) .sheet(isPresented: $isPresented) { VStack { NavigationStack { ScrollView { ForEach(0..<100, id: \.self) { number in Text("\(number)") } .frame(maxWidth: .infinity) } .background(.green) .presentationDetents([.medium]) } } } Here is what the issue looks like for this example. The issue occurs in: Simulator iPhone 16 iOS 18.4 Personal device (iPhone 16 iOS 18.4) Canvas preview
1
0
103
6d
Logic Pro cannot load v3 audio unit with framework compiled with Swift 6
Sequoia 15.4.1 (24E263) XCode: 16.3 (16E140) Logic Pro: 11.2.1 I’ve been developing a complex audio unit for Mac OS that works perfectly well in its own bespoke host app and is now well into its beta testing stage. It did take some effort to get it to work well in Logic Pro however and all was fine and working well until: The AU part is an empty app extension with a framework containing its code. The framework contains Swift code for the UI and C code for the DSP parts. When the framework is compiled using the Swift 5 compiler the AU will run in Logic with no problems. (I should also mention that AU passes the most strict auval tests). But… when the framework is compiled with Swift 6 Logic Pro cannot load it. Logic displays a message saying the audio unit could not be loaded and to contact the developer. My own host app loads the AU perfectly well with the Swift 6 version, so I know there’s nothing wrong with the audio unit. I cannot find any differences in any of the built output files except, of course, the actual binary code in the framework. I’ve worked for hours on this and cannot find a solution other than to build the framework in Swift 5. (I worked hard to get all the async code updated and working with Swift 6! so I feel a little cheated!) What is happening? Is this a bug in Logic? Is this a bug in Swift 6 compiler/linker? I’m at the Duh! hands in the air, tearing out hair stage! ( once again!)
1
0
277
6d
Extending @Model with custom macros
I am trying to extend my PersistedModels like so: @Versioned(3) @Model class MyType { var name: String init() { name = "hello" } } but it seems that SwiftData's@Model macro is unable to read the properties added by my @Versioned macro. I have tried changing the order and it ignores them regardless. version is not added to schemaMetadata and version needs to be persisted. I was planning on using this approach to add multiple capabilities to my model types. Is this possible to do with macros? VersionedMacro /// A macro that automatically implements VersionedModel protocol public struct VersionedMacro: MemberMacro, ExtensionMacro { // Member macro to add the stored property directly to the type public static func expansion( of node: AttributeSyntax, providingMembersOf declaration: some DeclGroupSyntax, in context: some MacroExpansionContext ) throws -> [DeclSyntax] { guard let argumentList = node.arguments?.as(LabeledExprListSyntax.self), let firstArgument = argumentList.first?.expression else { throw MacroExpansionErrorMessage("@Versioned requires a version number, e.g. @Versioned(3)") } let versionValue = firstArgument.description.trimmingCharacters(in: .whitespaces) // Add the stored property with the version value return [ "public private(set) var version: Int = \(raw: versionValue)" ] } // Extension macro to add static property public static func expansion( of node: SwiftSyntax.AttributeSyntax, attachedTo declaration: some SwiftSyntax.DeclGroupSyntax, providingExtensionsOf type: some SwiftSyntax.TypeSyntaxProtocol, conformingTo protocols: [SwiftSyntax.TypeSyntax], in context: some SwiftSyntaxMacros.MacroExpansionContext ) throws -> [SwiftSyntax.ExtensionDeclSyntax] { guard let argumentList = node.arguments?.as(LabeledExprListSyntax.self), let firstArgument = argumentList.first?.expression else { throw MacroExpansionErrorMessage("@Versioned requires a version number, e.g. @Versioned(3)") } let versionValue = firstArgument.description.trimmingCharacters(in: .whitespaces) // We need to explicitly add the conformance in the extension let ext = try ExtensionDeclSyntax("extension \(type): VersionedModel {}") .with(\.memberBlock.members, MemberBlockItemListSyntax { MemberBlockItemSyntax(decl: DeclSyntax( "public static var version: Int { \(raw: versionValue) }" )) }) return [ext] } } VersionedModel public protocol VersionedModel: PersistentModel { /// The version of this particular instance var version: Int { get } /// The type's current version static var version: Int { get } } Macro Expansion:
0
0
337
1w
Range For Keys and Values Of Dictionary
I came across a code let myFruitBasket = ["apple":"red", "banana": "yellow", "budbeeri": "dark voilet", "chikoo": "brown"] Can we have range for keys and values of dictionary, it will be convenient for keys print(myFruitBasket.keys[1...3]) // banana, budbeeri, chikoo same for values print(myFruitsBasket.values[1...3]) // yellow, voilet, brown
1
0
375
1w
fullscreencover Problem
Hello Apple Developer Community: I have a problem with the fullscreencover. I can see the Things, that shouldn’t be visible behind it. I’m currently developing with iOS 26 and only there it happens. I hope you can help me :) Have a nice day
1
3
39
1w