Search results for

Swift 6

49,205 results found

Post

Replies

Boosts

Views

Activity

Reply to Working with Input/Output stream with Swift 6 and concurrency framework
[quote='779913021, duoskater, /thread/779913, /profile/duoskater'] Also, are there any plans to migrate eg. CoreBluetooth stack to new swift 6 concurrency? [/quote] I can’t talk about The Future™. If you’d like to see improvements in this space, I recommend that you file an enhancement request explaining what you’re doing, what’s causing you grief, and what you’d like to see change. If you do file this, please post your bug number, just for the record. [quote='779913021, duoskater, /thread/779913, /profile/duoskater'] I wonder if something has changed in this regards? [/quote] Yes and no. Integrating run loop based APIs clearly into a Swift 6 codebase is still quite tricky. I’ve spent a bunch of time playing around with that lately and my conclusion was… yeah… try to avoid that if you can |-: There is one special case here, namely the main thread’s run loop. If you do all your run loop work on the main thread, things go relatively smoothly. Whether that’s practical or not depends on the natu
Apr ’25
Reply to Request authorization for the notification center crash iOS app on Swift 6
Thanks for the crash report. Consider this snippet: @MainActor var counter = 0 @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions …) -> Bool { counter += 1 let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound] UNUserNotificationCenter.current().requestAuthorization(options: authOptions) { _, _ in counter += 1 } return true } … } I’m compiling this with Xcode 16.0 in the Swift 6 language mode. The increments of counter show that Swift thinks that both application(_:didFinishLaunchingWithOptions:) and the closure are supposed to be running on the main actor. However, the closure called by requestAuthorization(options:completionHandler:) is documented to not run there. I’d expect that the compiler would insert code to ‘bounce’ to the main actor, but instead it inserted code to trap if it’s not on the main actor. I’m not sure why it thinks that in this context. Oh, and I checked with the lates
Topic: Programming Languages SubTopic: Swift Tags:
Sep ’24
Reply to @Observable in command line app
The topic is very interesting, and I humbly acknowledge that I haven’t grasped all the subtleties of Swift 6 (I’ll need to improve my skills on this subject). Here’s more information: my application takes input data and generates an output file. The file generation (which is complex) is carried out on a secondary thread (old school with GCD). Compatibility with Swift Concurrency is handled through a facade using withCheckedThrowingContinuation. The processes performed on the secondary thread (file creation) require configuration data that is used solely in a read-only way (the secondary thread does not modify this data, which is encapsulated in an object). In short, it looks something like this (names have been simplified for the example): Job (file creation on a secondary thread using GCD) AsyncJob (a facade over Job to ensure compatibility with Swift Concurrency) Configuration (data needed for the job processing) Code example: do { let configuration = Configuration(...) let job =
Topic: Programming Languages SubTopic: Swift Tags:
Oct ’24
Reply to System Network Extension and Sleep
I know you said to ignore this, but I want to post some info just in case other folks bump into it. For historical reasons, Network framework and Network Extension framework export different types with the same name. The list of such types includes NWPath and NWEndpoint. Historically: This caused ambiguous type problems if you imported both frameworks. The workaround was to fully qualify the name. So, instead of NWEndpoint, you would use Network.NWEndpoint or NetworkExtension.NWEndpoint. If that caused too much grief, you could deploy some type aliases: ### NWHelper.swift ### import Network typealias NWEndpoint = Network.NWEndpoint ### NEHelper.swift ### import NetworkExtension typealias NEEndpoint = NetworkExtension.NWEndpoint ### main.swift ### func test(endpointNW: NWEndpoint, endpointNE: NEEndpoint) { } This has changed in Xcode 16. If you’re in the Swift 5 language mode, things behave as they did previously. However, in the Swift 6 language mode the Network Extension types have been mad
Jan ’25
Type ReferenceWritableKeyPath does not conform to the 'Sendable' protocol
This is not a question but more of a hint where I was having trouble with. In my SwiftData App I wanted to move from Swift 5 to Swift 6, for that, as recommended, I stayed in Swift 5 language mode and set 'Strict Concurrency Checking' to 'Complete' within my build settings. It marked all the places where I was using predicates with the following warning: Type '' does not conform to the 'Sendable' protocol; this is an error in the Swift 6 language mode I had the same warnings for SortDescriptors. I spend quite some time searching the web and wrapping my head around how to solve that issue to be able to move to Swift 6. In the end I found this existing issue in the repository of the Swift Language https://github.com/swiftlang/swift/issues/68943. It says that this is not a warning that should be seen by the developer and in fact when turning Swift 6 language mode on those issues are not marked as errors. So if anyone is encountering this whe
3
0
984
Oct ’24
Reply to MPMediaItemPropertyArtwork crashes on Swift 6
I was gonna say that this looks remarkably like an issue I’ve been working on a different thread, but then I noticed that you’re the OP on that thread too. So, yeah, this is a similar issue and, as I mentioned over there, I’m still not 100% sure I fully understand all of these cases. However, I do have a suggestion for you. Consider this snippet: @MainActor class AudioPlayerProvider: ObservableObject { func setMetadataQ() { let defaultArtwork = UIImage(systemName: fireworks)! let nowPlayingInfo = [ MPMediaItemPropertyTitle: Hello, MPMediaItemPropertyArtist: Cruel World!, MPMediaItemPropertyArtwork: MPMediaItemArtwork(boundsSize: defaultArtwork.size) { _ in defaultArtwork }, ] as [String: Any] MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo } } @MainActor func test() { let o = AudioPlayerProvider() o.setMetadataQ() } I put this into a small test project, built it with Xcode 16.0 in Swift 6 mode, and ran on an iOS 18.0 device. It crashed exactly like your code. I resolved the crash by
Topic: Programming Languages SubTopic: Swift Tags:
Sep ’24
Why does a Swift test think my simple struct is main actor-isolated?
My experience with Swift 6 strict concurrency so far doesn't match my understanding of implicit MainActor isolation semantics. This is a cross-post from StackOverflow. I will link answers between both forums. TL;DR Build succeeds when testing a struct declared in the test module, but fails when the struct is moved to the main module: Main actor-isolated property … cannot be accessed from outside the actor. Steps to reproduce Open up Xcode 26 beta 2 on macOS 26 (probably also ok on current stables). Create a new Swift app with Swift testing, no storage. Call it WhatTheSwift. Set the Swift Language Version on all three targets to Swift 6. Update the default test file to be this: import Testing @testable import WhatTheSwift struct WhatTheSwiftTests { @Test func example() async throws { let thing = Thing(foo: bar) #expect(thing.foo == bar) } } struct Thing { let foo: String } That should build fine, and the tests should pass. Now, move the Thing declaration into its ow
2
0
183
Jun ’25
Reply to Bug fix
The issue here is that: The data race protection in Swift 6 requires that the compiler be able to understand the context in which code is run. Timer.scheduledTimer(…) runs the timer callback on the current run loop, which isn’t a concurrency mechanisms that the Swift compiler understands. Fixing this isn’t trivial in the general case, but there’s an easy fix in this case. You’re calling Timer.scheduledTimer(…) from a main-actor-isolated context, which means you’re on the main thread. Thus the timer will schedule its callback on the main thread’s run loop, and you just need to let the Swift compiler know that. The canonical way to do that is with MainActor.assumeIsolated(_:). For example: self.timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in MainActor.assumeIsolated { … the compiler now knows you’re on the main actor, trapping at runtime if that’s not the case … } } Pasted in below is a more complete example. Share and Enjoy — Quinn “The Eskimo!” @ Developer
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Dec ’24
Reply to Drag-and-Drop from macOS Safari to NSItemProvider fails due to URL not being a file:// URL
I also try to be a good app, and provide asynchronous support. I think that's your problem. It's too difficult to keep up with that. Your asynchronous code is already deprecated and disavowed. First of all, make sure you try using the ClipboardViewer tool. I think it's in Xcode's AdditionalTools as a separate download. I know you're dealing with Drag and Drop, which is not quite the same, but it may be enlightening as most people implement Copy and Paste with the same data. I've never tried dragging from Safari, but I certainly never seen any TIFF conversions. I even support data types that the system doesn't, so there's no way it ever could convert it. Again, I think you're trying too hard. Instead of itemProvider.loadInPlaceFileRepresentation, try just loadItem. That should give you the actual URL. You might run into concurrency problems. I seem to have encountered that myself with these APIs. Unfortunately, there's no easy solution. You definitely don't want to try those old dispatch queues, at least not i
Topic: UI Frameworks SubTopic: AppKit Tags:
1w
Main actor-isolated instance method 'locationManagerDidChangeAuthorization' cannot be used to satisfy nonisolated protocol requirement
I'm going through the migration to Swift 6 and I am running up with a few things. I have two view controllers which conform to the CLLocationManagerDelegate protocol. Both methods of the delegate have the same issue in my code. Below is an example of the warning received. Main actor-isolated instance method 'locationManagerDidChangeAuthorization' cannot be used to satisfy nonisolated protocol requirement; this is an error in the Swift 6 language mode
4
0
6.5k
Jul ’24
NSFileCoordinator Swift Concurrency
I'm working on implementing file moving with NSFileCoordinator. I'm using the slightly newer asynchronous API with the NSFileAccessIntents. My question is, how do I go about notifying the coordinator about the item move? Should I simply create a new instance in the asynchronous block? Or does it need to be the same coordinator instance? let writeQueue = OperationQueue() public func saveAndMove(data: String, to newURL: URL) { let oldURL = presentedItemURL! let sourceIntent = NSFileAccessIntent.writingIntent(with: oldURL, options: .forMoving) let destinationIntent = NSFileAccessIntent.writingIntent(with: newURL, options: .forReplacing) let coordinator = NSFileCoordinator() coordinator.coordinate(with: [sourceIntent, destinationIntent], queue: writeQueue) { error in if let error { return } do { // ERROR: Can't access NSFileCoordinator because it is not Sendable (Swift 6) coordinator.item(at: oldURL, willMoveTo: newURL) try FileManager.default.moveItem(at: oldURL, to: newURL) coordinator.item(at: oldURL,
0
0
65
Apr ’25
Reply to AVCam sample code build errors in Swift 6
@DTS Engineer I spent sometime and enabled concurrency checks to complete in the compiler options. I was able to fix two main sources of warning (which are error in Swift 6) by changing the definition of two functions as follows: func capturePhoto(with features: PhotoFeatures, isolation: isolated (any Actor)? = #isolation) async throws -> Photo func stopRecording(_ isolation: isolated (any Actor)? = #isolation) async throws -> Movie Effectively, I forced these functions to be called from the isolation domain of an Actor (which is actor CaptureService in the source code). I believe this should be okay as this is the only place where these functions are invoked. However, there is one place in the code where I still need help: ```` override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) { switch keyPath { case systemPreferredKeyPath: // Update the observer's system-preferred camera value. let newDevice = chang
Jan ’25
Xcode 16 Beta Swift Compiler Settings Missing
Really stumped on this issue my team is seeing with the Xcode 16 Beta (both Xcode 16 version 6 and Xcode 16.1). Wondering if anyone was having a similar issue and if this is a bug or something configured incorrectly. Basically, when I go to build settings and search for anything related to Swift Compiler nothing shows up. The only thing that appears with Swift in the title is under the User Defined keys (see attached) As such, I'm unable to change the Swift version for the project and I'm stuck in Swift 6 language mode which we're not quite ready for yet. This is only occurring on one of our targets. Our other app projects are behaving as expected. The project in question has the main target we build the project with and 2 support frameworks. The supporting frameworks are also working correctly. Its just the primary build target giving us fits. Curious if anyone is seeing something similar or has suggestions. Thanks!
9
0
2.8k
Sep ’24
Reply to WatchConnectivity Swift 6 - Incorrect actor executor assumption
I believe the crash (with the Incorrect actor executor assumption message) is intentional. When you use the Swift 6 mode to build your app, the compiler adds some runtime checks to detect problems that could otherwise cause a data race. If a check is not satisfied, it triggers a crash. I am by no means an expert of Swift compiler, but here is my theory about what happens in your case: a. ConnectivityManager is actor-isolated, meaning that, in your code snippet, self.session.sendMessageData(...), the replyHandler closure, and also the errorHandler closure are supposed to run in the actor's executor. b. WCSession.sendMessageData(...) doesn't really run replyHandler (or errorHandler) in the calling queue. This is mentioned in the API reference: If you specify a reply handler block, your handler block is executed asynchronously on a background thread. For some reason, the compiler doesn't detect the problem at the compile time, but at runtime, replyHandler (or errorHandler) is running in a queue
Jan ’25