Search results for

Swift 6

49,190 results found

Post

Replies

Boosts

Views

Activity

Crash in Swift 6 when using UNUserNotification
After porting code to Swift 6 (Xcode 16.4), I get a consistent crash (on simulator) when using UNUserNotificationServiceConnection It seems (searching on the web) that others have met the same issue. Is it a known Swift6 bug ? Or am I misusing UNUserNotification ? I do not have the crash when compiling on Xcode 26 ß5, which hints at an issue in Xcode 16.4. Crash log: Thread 10 Queue : com.apple.usernotifications.UNUserNotificationServiceConnection.call-out (serial) As far as I can tell, it seems error is when calling nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) I had to declare non isolated to solve a compiler error. Main actor-isolated instance method 'userNotificationCenter(_:didReceive:withCompletionHandler:)' cannot be used to satisfy nonisolated requirement from protocol 'UNUserNotificationCenterDelegate' I was advised to: Add
4
0
121
Aug ’25
Working with Input/Output stream with Swift 6 and concurrency framework
Hello, I am developing an application which is communicating with external device using BLE and L2CAP. I wonder what are the best practices of using Input & Output streams that are established with L2CAP connection when working with Swift 6 concurrency model. I've been trying to find some examples and hints for some time now but unfortunately there isn't much available. One useful thread I've found is: https://developer.apple.com/forums/thread/756281 but it does not offer much insight into using eg. actor model with streams. I wonder if something has changed in this regards? Also, are there any plans to migrate eg. CoreBluetooth stack to new swift 6 concurrency ?
2
0
93
Apr ’25
NSTextInputClient concurrency issues in Swift 6
Hello! In our codebase we have a NSView subclass that conforms to NSTextInputClient. This protocol is currently not marked as a main actor, but in the decade this has been in use here it has always been called on the main thread from AppKit. With Swift 6 (or complete concurrency checking in Swift 5) this conformance causes issues since NSView is a main actor but not this protocol. I've tried a few of the usual fixes (MainActor.assumeIsolated or prefixing the protocol conformance with @preconcurrency) but they were not able to resolve all warnings. So I dug in the AppKit headers and found that NSTextInputClient is usually implemented by the view itself, but that that is not a hard requirement (see NSTextInputContext.h the documentation for the client property or here). With that I turned my NSView subclass extension into a separate class that is not a main actor and in my NSView subclass create an instance of it and NSTextInputContext. This all seems to work fine in my initial tests, the dele
0
0
591
Jun ’24
Calling `requestAuthorization(options:completionHandler:)` in Swift 6 leads to `EXC_BAD_INSTRUCTION` crash.
I am in the process of evaluating Swift 6 and I noticed that when using the completion handler version of the requestAuthorization the application crashes with EXC_BAD_INSTRUCTION exception. Using this code: let center = UNUserNotificationCenter.current() center.requestAuthorization(options: [.alert, .sound, .badge]) { success, error in print(success) } Crashes when the project is build with Swift 6 and works normalising when build with Swift 5. The only solution that I have found so far is to switch to using the async version of that API: Task { let center = UNUserNotificationCenter.current() do { if try await center.requestAuthorization(options: [.alert, .sound, .badge]) == true { print(success) } else { print(fail) } } catch { print(Error) } } Is the a known issue? I have submitted feedback with ID FB15294185.
3
0
831
Sep ’24
SwiftUI View cannot conform custom Equatable protocol in Swift 6.
In Swift 6, stricter concurrency rules can lead to challenges when making SwiftUI views conform to Equatable. Specifically, the == operator required for Equatable must be nonisolated, which means it cannot access @MainActor-isolated properties. This creates an error when trying to compare views with such properties: Error Example: struct MyView: View, Equatable { let title: String let count: Int static func ==(lhs: MyView, rhs: MyView) -> Bool { // Accessing `title` here would trigger an error due to actor isolation. return lhs.count == rhs.count } var body: some View { Text(title) } } Error Message: Main actor-isolated operator function '==' cannot be used to satisfy nonisolated protocol requirement; this is an error in the Swift 6 language mode. Any suggestions? Thanks FB: FB15753655 (SwiftUI View cannot conform custom Equatable protocol in Swift 6.)
6
0
928
Nov ’24
Swift 6 Concurrency Errors with MKLocalSearchCompleterDelegate results
Has anyone found a thread-safe pattern that can extract results from completerDidUpdateResults(MKLocalSearchCompleter) in the MKLocalSearchCompleterDelegate ? I've downloaded the code sample from Interacting with nearby points of interest and notice the conformance throws multiple errors in Xcode 16 Beta 5 with Swift 6: extension SearchDataSource: MKLocalSearchCompleterDelegate { nonisolated func completerDidUpdateResults(_ completer: MKLocalSearchCompleter) { Task { let suggestedCompletions = completer.results await resultStreamContinuation?.yield(suggestedCompletions) } } Error: Task-isolated value of type '() async -> ()' passed as a strongly transferred parameter; later accesses could race and Error: Sending 'suggestedCompletions' risks causing data races Is there another technique I can use to share state of suggestedCompletions outside of the delegate in the code sample?
4
0
2.1k
Aug ’24
Model Container Sendable Throwing Error in Swift 6
Hi all, I just wanted to ask how people were using ModelActor with the Swift 6 language mode enabled. My current implementation involves passing the ModelContainer to my ModelActor, which worked in Sonoma and previous betas of Sequoia, however in the current Beta 3, I get this error: Sending 'self.modelContext.container' risks causing data races I am a bit confused by this, as from what I understand, ModelContainer conforms to Sendable, so ideally this error should not be thrown. Is this a bug in Beta 3? Thanks in advance.
3
0
1.4k
Jul ’24
Core Data, Swift 6, Concurrency and more
I have the following struct doing some simple tasks, running a network request and then saving items to Core Data. Per Xcode 26's new default settings (onisolated(nonsending) & defaultIsolation set to MainActor), the struct and its functions run on the main actor, which works fine and I can even safely omit the context.perform call because of it, which is great. struct DataHandler { func importGames(withIDs ids: [Int]) async throws { ... let context = PersistenceController.shared.container.viewContext for game in games { let newGame = GYGame(context: context) newGame.id = UUID() } try context.save() } } Now, I want to run this in a background thread to increase performance and responsiveness. So I followed this session (https://developer.apple.com/videos/play/wwdc2025/270) and believe the solution is to mark the struct as nonisolated and the function itself as @concurrent. The function now works on a background thread, but I receive a crash: _dispatch_assert_queue_fail. This happens whether I wrap the Cor
2
0
96
Jun ’25
Logic Pro loads AUv3 when compiled in Swift 5 but not Swift 6
I have spent a long time refactoring lots of older Swift code to compile without error in Swift 6. The app is a v3 audio unit host and audio unit. Having installed Sonoma and XCode 16 I compile the code using Swift 6 and it compiles and runs without any warnings or errors. My host will load my AU no problem. LOGIC PRO is still the ONLY audio unit host that will load native Mac V3 audio units and so I like to test my code using Logic. In Sonoma with XCode 16... My AU passes the most stringent AUVAL tests both in terminal and Logic pro. If I compile the AU source in Swift 5 Logic will see the AU, load it and run it without problems. But when I compile the AU in Swift 6 Logic sees the AU, will scan it and verify it passes the tests but will not load the AU. In XCode I see a log message that a helper application failed to run but the debugger never connects to the AU and I don't think Logic even gets as far as instantiating the AU. So... what is causing this? I'm stump
1
0
477
Jan ’25
AVAudioPlayerNode scheduleBuffer & Swift 6 Concurrency
We do custom audio buffering in our app. A very minimal version of the relevant code would look something like: import AVFoundation class LoopingBuffer { private var playerNode: AVAudioPlayerNode private var audioFile: AVAudioFile init(playerNode: AVAudioPlayerNode, audioFile: AVAudioFile) { self.playerNode = playerNode self.audioFile = audioFile } func scheduleBuffer(_ frames: AVAudioFrameCount) async { let audioBuffer = AVAudioPCMBuffer( pcmFormat: audioFile.processingFormat, frameCapacity: frames )! try! audioFile.read(into: audioBuffer, frameCount: frames) await playerNode.scheduleBuffer(audioBuffer, completionCallbackType: .dataConsumed) } } We are in the migration process to swift 6 concurrency and have moved a lot of our audio code into a global actor. So now we have something along the lines of import AVFoundation @globalActor public actor AudioActor: GlobalActor { public static let shared = AudioActor() } @AudioActor class LoopingBuffer { private var playerNode: AVAudioPlayerNode private var
3
0
1k
Aug ’24
Playground Macro Raises Error when compiled with Swift 6
In my Xcode app, I was attempting to use the #Playground macro to play around with some of the Foundation Model features to see if they would work for my iOS app. However, every time I used a #Playground macro, even if it was empty, it would receive the following error: /var/folders/q2/x5b9x0y161bb2l_0yj1_j6wm0000gn/T/swift-generated-sources/@__swiftmacro_20PlaygroundMacroIssue0022ContentViewswift_tiAIefMX26_0_33_B691877350F20F2DFC040B9E585F4D10Ll0A0fMf_.swift:51:5 Main actor-isolated let '$s20PlaygroundMacroIssue0022ContentViewswift_tiAIefMX26_0_33_B691877350F20F2DFC040B9E585F4D10Ll0A0fMf_23PlaygroundContentRecordfMu_' can not be referenced from a nonisolated context Here are my Xcode and system versions: Mac is running the first public beta of Tahoe. iOS Simulator is running 26.0 dev beta 4. Xcode is Xcode 26 beta 4. So, I went to try to reproduce the error in a blank iOS app project (the error above is the one that I reproduced in that project). Here are the steps that I took. I created a
2
0
94
Jul ’25
Metal addCompletedHandler causes crash with Swift 6 (iOS)
The following code runs fine when compiled with Swift 5, but crashes when compiled with Swift 6 (stack trace below). In the draw method, commenting out the addCompletedHandler line fixes the problem. I'm testing on iOS 18.0 and see the same behavior in both the simulator and on a device. What's going on here? import Metal import MetalKit import UIKit class ViewController: UIViewController { @IBOutlet var metalView: MTKView! private var commandQueue: MTLCommandQueue? override func viewDidLoad() { super.viewDidLoad() guard let device = MTLCreateSystemDefaultDevice() else { fatalError(expected a Metal device) } self.commandQueue = device.makeCommandQueue() metalView.device = device metalView.enableSetNeedsDisplay = true metalView.isPaused = true metalView.delegate = self } } extension ViewController: MTKViewDelegate { func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) {} func draw(in view: MTKView) { guard let commandQueue, let commandBuffer = commandQueue.makeCommandBuffer() el
3
0
930
Sep ’24
Core Data + CKSyncEngine with Swift 6 — concurrency, Sendable, and best practices validation
Hi everyone, I’ve been working on migrating my app (SwimTimes, which helps swimmers track their times) to use Core Data + CKSyncEngine with Swift 6. After many iterations, forum searches, and experimentation, I’ve created a focused sample project that demonstrates the architecture I’m using. The good news: 👉 I believe the crashes I was experiencing are now solved, and the sync behavior is working correctly. 👉 The demo project compiles and runs cleanly with Swift 6. However, before adopting this as the final architecture, I’d like to ask the community (and hopefully Apple engineers) to validate a few critical points, especially regarding Swift 6 concurrency and Core Data contexts. Architecture Overview Persistence layer: Persistence.swift sets up the Core Data stack with a main viewContext and a background context for CKSyncEngine. Repositories: All Core Data access is abstracted into repository classes (UsersRepository, SwimTimesRepository), with async/await methods. SyncEngine: W
1
0
333
1w
Core Data and Swift 6 concurrency: returning an NSManagedObject
We're in the process of migrating our app to the Swift 6 language mode. I have hit a road block that I cannot wrap my head around, and it concerns Core Data and how we work with NSManagedObject instances. Greatly simplied, our Core Data stack looks like this: class CoreDataStack { private let persistentContainer: NSPersistentContainer var viewContext: NSManagedObjectContext { persistentContainer.viewContext } } For accessing the database, we provide Controller classes such as e.g. class PersonController { private let coreDataStack: CoreDataStack func fetchPerson(byName name: String) async throws -> Person? { try await coreDataStack.viewContext.perform { let fetchRequest = NSFetchRequest() fetchRequest.predicate = NSPredicate(format: name == %@, name) return try fetchRequest.execute().first } } } Our view controllers use such controllers to fetch objects and populate their UI with it: class MyViewController: UIViewController { private let chatController: PersonController private let ageLabel: UILab
0
0
65
Apr ’25
Crash in AVCaptureDevice.requestAccess in iOS 18 with swift 6
I am facing an issue in iOS 18 that works fine in iOS 17 and earlier. This happens when you set the project to use Swift 6, if you set swift 5 this will work ok. The app has the Privacy - Camera Usage Description key in the Info.plist. It is a wrapper that implements UIViewControllerRepresentable to create the UIViewController. This wrapper is within a view that gets pushed when the user presses a button (see snippet code below). Sometimes, I get a popup asking for permission to access the camera, and the app crashes immediately. Other times, I don’t see the popup, and the app crashes right away. I tried adding Task { @MainActor } within the requestAccess closure, but it did not resolve the issue. It does not matter the code within the closure; it crashes even if the closure is empty. The crash trace shows _dispatch_assert_queue_fail (see the attached image). Has anyone else experienced this issue? Any insights would be greatly appreciated. The following code will crash if run as is. ***** P
1
0
450
Feb ’25