Search results for

Swift 6

49,201 results found

Post

Replies

Boosts

Views

Activity

Reply to Swift6 race warning
I tried a bunch of things but wasn’t able to reproduce this. Here’s an example of what I did: import Foundation import Photos @MainActor func show(imageInfo: (path: String, asset: PHAsset?)) { } class Test { func onCaptureCompleted(_ imageURL: URL, asset: PHAsset?) { let path = imageURL.path() Task { @MainActor in show(imageInfo: (path, asset)) } } } func main() { print(Hello Cruel World!) } main() This compiles just fine with Xcode 16.2 in Swift 6 language mode. Which version of Xcode are you using? Can you post a snippet that shows the problem? Please post it as text rather than an image. See tips 5 and 6 in Quinn’s Top Ten DevForums Tips. Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = eskimo + 1 + @ + apple.com
Topic: Programming Languages SubTopic: Swift Tags:
Jan ’25
Reply to How to upgrade my project to Swift 6.2
Right. There are two terms you need to understand here: Swift compiler version Swift language mode This terminology is defined (recently mind you) in SE-0441 Consider this: % DEVELOPER_DIR=/Users/quinn/XcodeZone/Xcode-beta.app/Contents/Developer xcrun swift --version swift-driver version: 1.127.5.3 Apple Swift version 6.2 … The Swift compiler version build in to Xcode 26.0b2 is 6.2. That compiler supports multiple language modes, and Xcode it show you those in that popup. There is no Swift 6.2 language mode, and that’s fine. Having said that, the Swift 6 language mode in Swift 6.2 does have optional features that are likely important to you. The most important of those is the approachable concurrency features, controlled by the Approachable Concurrency (SWIFT_APPROACHABLE_CONCURRENCY) build setting. Note that it’s possible that Swift might gain a future language mode to cover stuff like this, but that’s a topic for Swift
Topic: Programming Languages SubTopic: Swift Tags:
Jul ’25
NSHostingView Not Working With Swift 6.0
I recently compiled my macOS App with Swift 6 in Xcode 16 (was using Swift 5 previously) and noticed that AppKit Integration doesn't appear to be working as before. All my instances of NSHostingView which allow me to add a SwiftUI View to an AppKit NSWindow view controller no longer respond to mouse input anymore. All my NSHostingView instances display but refuse to accept any user interaction. Has anyone else noticed this and is there a workaround to get NSHostingView to once again be able to accept user/mouse events with Swift 6?
8
0
1.3k
Jul ’24
Reply to Should ModelActor be used to populate a view?
It's unclear what LabResultDto in the code snippet is. If it is a Sendable type that wraps the data in a SwiftData model, that's fine; if it is a SwiftData model type, because a SwiftData model object is not Sendable, you won't want to pass it across actors – Otherwise, Swift 6 compiler will give you an error. For more information about this topic, see the discussion here. When using SwiftData + SwiftUI, I typically use @Query to create a result set for a view. Under the hood (of @Query), the query controller should be able to detect the changes you made from within a model actor, and trigger a SwiftUI update. Fore more information about observing SwiftData changes, see this WWDC25 video. Best, —— Ziqiao Chen  Worldwide Developer Relations.
Topic: UI Frameworks SubTopic: SwiftUI Tags:
2w
Reply to Swift 6 concurrency - Xcode 16b5 - init() is always nonisolated?
I'm also having problems with NSObjects in 16b5. With complete concurrency checking enabled but Swift 5 language mode, the following generates 1 warning and 1 error: import Foundation import UIKit @MainActor class TestObject: NSObject { let testView = UIView(frame: .zero) private func doSomething() { } override init() { // [ERROR] Property 'self.testView' not initialised at super.init call super.init() // [WARNING] Call to main actor-isolated instance method 'doSomething()' in a synchronous nonisolated context; this is an error in the Swift 6 language mode doSomething() } } So, (1) what's up with the let call not instantiating before the init() is called? and (2) how come the override method is now reverting back to the solution of the function being overridden rather than the stated actor/isolation of the object it's being defined in? I really hope Quin's about to put me straight.
Aug ’24
Reply to WKScriptMessageHandlerWithReply and strict concurrency checking
But since WKScriptMessageHandlerWithReply is not @MainActor, neither can this method be so marked My WebKit is kinda rusty but I believe that WKScriptMessageHandlerWithReply should be as main-actor isolated, right? That is, all of its methods are expected to be called on the main thread? If so, this devolves into the question “How do I tell the Swift compiler about that fact?” There are various tricks for that but I tend to reach for MainActor.assumeIsolated(_:file:line:): @MainActor class MyClass: NSObject, WKScriptMessageHandlerWithReply { var lastMessage: WKScriptMessage? = nil var counter: Int = 0 nonisolated func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage, replyHandler: @escaping (Any?, String?) -> Void) { MainActor.assumeIsolated { self.lastMessage = message self.counter += 1 replyHandler([counter: self.counter], nil) } } } This compiles without warnings in Xcode 15.3 with strict concurrency enabled. Now how it’s accessing coun
Topic: Programming Languages SubTopic: Swift Tags:
May ’24
Reply to UIDevice: Main actor-isolated class property 'current' can not be referenced from a non-isolated context
Thank you, @Frameworks Engineer! In my case your comment helped me a lot. In my app I need to differentiate an iPhone device from other devices like iPad, Mac, etc. because on iPhone I must not select by default first element in my Navigation List, but I must do this on other devices. Initially I was checking like this: if !UIDevice.current.model.starts(with: iPhone) { ... } but it showed me this warning Main actor-isolated class property 'current' can not be referenced from a non-isolated context; this is an error in Swift 6 for such check within the (try? await ...) block. I was curious why, but now I understand, it's because UIDevice is only supported on the main thread. So, now I'm getting the value at once in the beginning: private let device = UIDevice.current.model and then just check the device in other places: if !device.starts(with: iPhone) { ... }
Topic: UI Frameworks SubTopic: UIKit Tags:
Jul ’24
CoreBluetooth and Swift strict concurrency checking
As of iOS 18.3 SDK, Core Bluetooth is still mostly an Objective-C framework: key objects like CBPeripheral inherit from NSObjectProtocol and does not conform to Sendable. CBCentralManager has a convenience initializer that allows the caller to provide a dispatch_queue for delegate callbacks. I want my Swift package that implements Core Bluetooth to conform to Swift 6 strict concurrency checking. It is unsafe to dispatch the delegate events onto my own actor, as the passed in objects are presumably not thread-safe. What is the recommended concurrency safe way to implement Core Bluetooth in Swift 6 with strict concurrency checking enabled?
0
0
96
Mar ’25
Reply to Live activity sample code for Swift 6?
Ok, specific problem then. I downloaded Emoji Rangers, switched language mode to Swift 6, udpated some static vars to static lets, commented out the contents of ImageURLProtocol.stopLoading and finally got to the issue in AdventureView.swift: This error is the one I can't seem to solve - Main actor-isolated value of type '() async -> Void' passed as a strongly transferred parameter; later accesses could race. As far as I understand it, here it basically means that something that is not Sendable is being sent between contexts. It is not possible to remove @MainActor here because activityViewState is isolated to it: And even if this was not a factor, the original error reappears once activityViewState is no longer in the picture: The only workaround I've found feels wrong: extension Activity: @unchecked @retroactive Sendable {}
Topic: App & System Services SubTopic: General Tags:
Sep ’24
Reply to Doubts about running new syntax in an older version of Swift
That setting doesn’t control the Swift compiler version. You always get the Swift compiler that’s built in to Xcode [1]. Rather, it controls the Swift language version, that is, the version of the language that the compiler tries to accommodate. The language version matters in the rare cases where Swift changes behaviour in some incompatible way. The language version don’t limit what features you can use. So you’ll find that many Swift 5 features are available when the language version is set to Swift 4.2, as long as those features don’t cause source-level compatibility problems for existing Swift 4.2 source code. I say “rare cases”, and that’s been true recently. However, the upcoming Swift 6 is going to involve a lot of changes, enforcing data race safety. Given that context, now is a good time to move forward to Swift 5. And, if you’re writing concurrent code, enable Strict Concurrency Checking. Share and Enjoy — Quinn “The Es
Topic: Programming Languages SubTopic: Swift Tags:
Apr ’24
Reply to How to enforce Swift 5.8.1 compiler to require explicit existential `any` keyword?
Making any required is a feature that's going to be enforced in Swift 6, but that's still a way off in the future. SE-0362 introduced a way to opt in to such future features, and the any requirement is listed as one such, under the identifier ExistentialAny. You'll need to pass this to the compiler in a -enable-upcoming-feature ExistentialAny compiler flag. Regarding main.swift, it sounds like you've manually created a main.swift and you're also using the @main construct from whichever app lifecycle template you chose when creating the project. Those will conflict. If you're using the SwiftUI lifecycle, you should use @UIApplicationDelegateAdaptor to get an app delegate. If not, use @main in the app delegate class declaration instead. Either way, you don't need to (and shouldn't) create a main.swift file.
Topic: Programming Languages SubTopic: Swift Tags:
Aug ’23
How to adapt RunLoop to swift concurrency(async/await)
I'm having some compilation warnings using Xcode 14.2/swift 5.7 (future errors in swift 6). I've some async function tests in a unit test target which include some code to process UI changes in the main loop. There are two related warnings: RunLoop.current.run(until: Date()) // which raises next warning Class property 'current' is unavailable from asynchronous contexts; currentRunLoop cannot be used from async contexts.; this is an error in Swift 6 CFRunLoopRunInMode(CFRunLoopMode.defaultMode, 0.1, false) // which raises next warning Global function 'CFRunLoopRunInMode' is unavailable from asynchronous contexts; CFRunLoopRunInMode cannot be used from async contexts.; this is an error in Swift 6 Here a full function test example. @MainActor func testBasic() async throws { // GIVEN sut = MainViewController(nibName: nil, bundle: nil) present(viewController: sut) // WHEN sut.loadViewIfNeeded() sut.showLoading() RunLoop.current.run(until: Date()) sut.hideLoading() sut.showNoConn
4
0
3.9k
Dec ’22
Reply to How to fix this Swift 6 migration issue?
Note how addPeriodicTimeObserver(…) takes a queue parameter which tells the system the queue on which to run the observer. You’re passing .main, indicating that you want the observer to run on the main queue. In that case, you don’t need to spin up a task. Rather, you can use assumeIsolate(…), which has two functions: At compile time, it tells the compiler that you’re expecting this code to run on the main actor. At runtime, it checks that fact. So, your code might look like this: avPlayer.addPeriodicTimeObserver(forInterval: CMTime(value: 1, timescale: 60), queue: .main) { [weak self] _ in MainActor.assumeIsolated { self?.myMainActorIsolatedMethod() } } There are a bunch of recipes like this in the Migrating to Swift 6 doc. Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = eskimo + 1 + @ + apple.com
Topic: Programming Languages SubTopic: Swift Tags:
Sep ’24
Reply to @Observable in command line app
Yeah, that’s a common pitfall. [quote='810625022, Capablanca, /thread/766993?answerId=810625022#810625022, /profile/Capablanca'] Does the following code seem correct to you? [/quote] Yes. And no (-: More below. [quote='810625022, Capablanca, /thread/766993?answerId=810625022#810625022, /profile/Capablanca'] I added the observe method [/quote] Yeah, this recursive structure is the standard way of handling this. The only problem with your code is that it falls foul of Swift 6’s data race checking: observe(job: job) // ^ Capture of 'job' with non-sendable type 'AsyncJob' in a `@Sendable` closure It’s hard for me to recommend a fix for that, because it’s tied into your overall concurrency strategy. Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = eskimo + 1 + @ + apple.com
Topic: Programming Languages SubTopic: Swift Tags:
Oct ’24