Discuss Swift.

Swift Documentation

Post

Replies

Boosts

Views

Activity

Sending 'self' risks causing data races
Hi! I'm trying to implement Swift 6 in my code but can't fix one problem. Here is my code example which could be run in playground: import UIKit import WatchConnectivity public final class MulticastDelegate<T>: Sendable { nonisolated(unsafe) private var delegates = [WeakWrapper]() public init() { } public var isEmpty: Bool { return delegates.isEmpty } public func addDelegate(_ delegate: T) { let wrapper = WeakWrapper(value: delegate as AnyObject) delegates.append(wrapper) } public func removeDelegate(_ delegate: T) { delegates = delegates.filter { $0.value !== delegate as AnyObject } } public func invokeDelegates(_ invocation: (T) -> Void) { for (index, delegate) in delegates.enumerated().reversed() { if let delegate = delegate.value as? T { invocation(delegate) } else { delegates.remove(at: index) } } } public func invokeDelegatesCheckingResponse(_ invocation: (T) -> Bool) -> Bool { var isHandled = false for delegate in delegates { if let delegate = delegate.value as? T { if invocation(delegate) { isHandled = true break } } } return isHandled } private final class WeakWrapper: Sendable { nonisolated(unsafe) weak var value: AnyObject? init(value: AnyObject) { self.value = value } } } @globalActor public actor WatchActor { public static var shared = WatchActor() } @MainActor @objc public protocol WatchCommunicatorDelegate: NSObjectProtocol { @objc optional func watchCommunicatorDidRequestDataUpdate(_ controller: WatchCommunicator) } @WatchActor @objc public final class WatchCommunicator: NSObject { private let multicastDelegate = MulticastDelegate<WatchCommunicatorDelegate>() } extension WatchCommunicator: @preconcurrency WCSessionDelegate { public func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: (any Error)?) { multicastDelegate.invokeDelegates { delegate in Task { @MainActor in delegate.watchCommunicatorDidRequestDataUpdate?(self) } } } public func sessionDidBecomeInactive(_ session: WCSession) { } public func sessionDidDeactivate(_ session: WCSession) { } } I want to work with WatchCommunicator in global actor and WatchCommunicatorDelegate should be call in main actor and should have reference to WatchCommunicator. Help please
2
0
507
Oct ’24
Xcode "Build documentation" not working with Swift Macro package in project
I have a workspace with my project and a Swift Macro. When I use the "Build Documentation" command the build fails with this error: fatal error: module map file '/Users/me/Library/Developer/Xcode/DerivedData/Project-fmdkuqlofexbqdhhitpgjnoqzyrz/Build/Intermediates.noindex/GeneratedModuleMaps-iphoneos/Macros.modulemap' not found Is there a way around this?
2
1
757
Feb ’24
MPMediaItemPropertyArtwork crashes on Swift 6
Hey all! in my personal quest to make future proof apps moving to Swift 6, one of my app has a problem when setting an artwork image in MPNowPlayingInfoCenter Here's what I'm using to set the metadata func setMetadata(title: String? = nil, artist: String? = nil, artwork: String? = nil) async throws { let defaultArtwork = UIImage(named: "logo")! var nowPlayingInfo = [ MPMediaItemPropertyTitle: title ?? "***", MPMediaItemPropertyArtist: artist ?? "***", MPMediaItemPropertyArtwork: MPMediaItemArtwork(boundsSize: defaultArtwork.size) { _ in defaultArtwork } ] as [String: Any] if let artwork = artwork { guard let url = URL(string: artwork) else { return } let (data, response) = try await URLSession.shared.data(from: url) guard (response as? HTTPURLResponse)?.statusCode == 200 else { return } guard let image = UIImage(data: data) else { return } nowPlayingInfo[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(boundsSize: image.size) { _ in image } } MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo } the app crashes when hitting MPMediaItemPropertyArtwork: MPMediaItemArtwork(boundsSize: defaultArtwork.size) { _ in defaultArtwork } or nowPlayingInfo[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(boundsSize: image.size) { _ in image } commenting out these two make the app work again. Again, no clue on why. Thanks in advance
6
0
514
Sep ’24
Crash with Progress type, Swift 6, iOS 18
We are getting a crash _dispatch_assert_queue_fail when the cancellationHandler on NSProgress is called. We do not see this with iOS 17.x, only on iOS 18. We are building in Swift 6 language mode and do not have any compiler warnings. We have a type whose init looks something like this: init( request: URLRequest, destinationURL: URL, session: URLSession ) { progress = Progress() progress.kind = .file progress.fileOperationKind = .downloading progress.fileURL = destinationURL progress.pausingHandler = { [weak self] in self?.setIsPaused(true) } progress.resumingHandler = { [weak self] in self?.setIsPaused(false) } progress.cancellationHandler = { [weak self] in self?.cancel() } When the progress is cancelled, and the cancellation handler is invoked. We get the crash. The crash is not reproducible 100% of the time, but it happens significantly often. Especially after cleaning and rebuilding and running our tests. * thread #4, queue = 'com.apple.root.default-qos', stop reason = EXC_BREAKPOINT (code=1, subcode=0x18017b0e8) * frame #0: 0x000000018017b0e8 libdispatch.dylib`_dispatch_assert_queue_fail + 116 frame #1: 0x000000018017b074 libdispatch.dylib`dispatch_assert_queue + 188 frame #2: 0x00000002444c63e0 libswift_Concurrency.dylib`swift_task_isCurrentExecutorImpl(swift::SerialExecutorRef) + 284 frame #3: 0x000000010b80bd84 MyTests`closure #3 in MyController.init() at MyController.swift:0 frame #4: 0x000000010b80bb04 MyTests`thunk for @escaping @callee_guaranteed @Sendable () -&gt; () at &lt;compiler-generated&gt;:0 frame #5: 0x00000001810276b0 Foundation`__20-[NSProgress cancel]_block_invoke_3 + 28 frame #6: 0x00000001801774ec libdispatch.dylib`_dispatch_call_block_and_release + 24 frame #7: 0x0000000180178de0 libdispatch.dylib`_dispatch_client_callout + 16 frame #8: 0x000000018018b7dc libdispatch.dylib`_dispatch_root_queue_drain + 1072 frame #9: 0x000000018018bf60 libdispatch.dylib`_dispatch_worker_thread2 + 232 frame #10: 0x00000001012a77d8 libsystem_pthread.dylib`_pthread_wqthread + 224 Any thoughts on why this is crashing and what we can do to work-around it? I have not been able to extract our code into a simple reproducible case yet. And I mostly see it when running our code in a testing environment (XCTest). Although I have been able to reproduce it running an app a few times, it's just less common.
23
7
979
Oct ’24
@Observation: Best way of handling binding after injecting a View-Model
In WWDC 2023 there was a good summary of how to handle the iOS 17 Observation capability. But despite the clear graphics, it was still ambiguous (for me.) I want to inject a class (view-model) so that it can be used in the complete view heirarchy, and used in bindings to allow bi-directional communication. As far as I can tell there are 2 ways of declaring the VM (alternatives 1 and 2 in my code), and 2 ways of consuming the VM in a view (alternatives 3 and 4 in my code). Using the flow-diagram I can't determine which is best. Here's the crux of my #Observable problem. import SwiftUI // MARK: - Model struct MyMod { var title = "Hello, World!" } // MARK: - MVV @Observable class MyMVV { var model: MyMod init() { self.model = MyMod() } } // MARK: - App @main struct MyApp: App { @Bindable var myGlobalMVV = MyMVV() // Alternative 1 // @State var myGlobalMVV = MyMVV() // Alternative 2 var body: some Scene { WindowGroup { ContentView() .environment(myGlobalMVV) // inject } } } struct ContentView: View { var body: some View { ContentDeepHierarchyView() } } struct ContentDeepHierarchyView: View { @Environment(MyMVV.self) var myGlobalMVV // digest var body: some View { @Bindable var myLocalMVV = myGlobalMVV // Alternative 3 TextField("The new title", text: $myLocalMVV.model.title) // Alternative 3 TextField("The new title", text: Bindable(myGlobalMVV).model.title) // Alternative 4 } Opinions?
0
0
278
Oct ’24
Getting error on xcode 15.3 underlying Objective-C module 'FirebaseSharedSwift' not found
underlying Objective-C module 'FirebaseSharedSwift' not found aymodazhnyneylcscdggrsgjocui/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/FirebaseSharedSwift.build/Objects-normal/x86_64/FirebaseSharedSwift.private.swiftinterface:5:19: underlying Objective-C module 'FirebaseSharedSwift' not found Command SwiftCompile failed with a nonzero exit code
0
0
242
Oct ’24
The compiler is unable to type-check this expression in reasonable time
This is one of the worst errors you can encounter while developing with Xcode. It looks like it's related to a problem inside the compiler itself: when there are lot of lines of code, it becomes unable to identify them all and start asking you to break down the code in smaller pieces. Sometimes you can, sometimes not. First of all, in your code there is FOR SURE an error, so in case of the second option, begin commenting entires sections of your code: this can lead to two options: You commented a section that contains the error: Xcode give you the preview and you check the commented section to find the error You commented enough code to let the compiler do its job, and you'll have the normal error reported in your code: again, fix it! Once errors have been fixed, normally you can uncomment what you excluded and all will go up and ok again. The most common errors that can lead to this behavior (but it's just a hint) are those involving parameters got or passed to other SwiftUI objects: parameters label (mistyped, missing, exceeding) parameters values (not $/& present, $/& present but not required) parameters types (you passed a wrong type) Well, I hope that this post could be useful to others that, like I did, are struggling a lot to understand the exact nature of this peculiar error. Code well and Prosper!
0
1
199
Oct ’24
async let combination crashes on XCode 16 with iOS 15 as minimum deployment
We started building our project in XCode 16 only to find a super weird crash that was 100% reproducible. I couldn't really understand why it was crashing, so I tried to trim down the problematic piece of code to something that I could provide in a side project. The actual piece of code crashing for us is significantly different, but this small example showcases the crash as well. https://github.com/Elih96/XCode16CrashReproducer our observation is, that this combination of async let usage + struct structure leads to a SIGABRT crash in the concurrency library. In both the main project and the example project, moving away from async let and using any other concurrency mechanism fixes the crash. This was reproducible only on Xcode 16 with iOS 15 set as minimum deployment for the target. It works fine on Xcode 15, and if we bump the min deployment to 16 on Xcode 16, it also runs fine. I've attached a small project that reproduces the error. I'm sure I didn't provide the ideal reproduction scenario, but that's what I managed to trim it down to. Making random changes such as removing some properties from the B struct or remove the: let _ = A().arrayItems.map { _ in "123" } will stop the crash from happening, so I just stopped making changes. The stack trace from the crash: frame #0: 0x00000001036d1008 libsystem_kernel.dylib`__pthread_kill + 8 frame #1: 0x0000000102ecf408 libsystem_pthread.dylib`pthread_kill + 256 frame #2: 0x00000001801655c0 libsystem_c.dylib`abort + 104 frame #3: 0x000000020a8b7de0 libswift_Concurrency.dylib`swift::swift_Concurrency_fatalErrorv(unsigned int, char const*, char*) + 28 frame #4: 0x000000020a8b7dfc libswift_Concurrency.dylib`swift::swift_Concurrency_fatalError(unsigned int, char const*, ...) + 28 frame #5: 0x000000020a8baf54 libswift_Concurrency.dylib`swift_task_dealloc + 124 frame #6: 0x000000020a8b72c8 libswift_Concurrency.dylib`asyncLet_finish_after_task_completion(swift::AsyncContext*, swift::AsyncLet*, void (swift::AsyncContext* swift_async_context) swiftasynccall*, swift::AsyncContext*, void*) + 72 * frame #7: 0x000000010344e6e4 CrashReproducer.debug.dylib`closure #1 in closure #1 in CrashReproducerApp.body.getter at CrashReproducerApp.swift:17:46 frame #8: 0x00000001cca0a560 SwiftUI`___lldb_unnamed_symbol158883 frame #9: 0x00000001cca09fc0 SwiftUI`___lldb_unnamed_symbol158825 frame #10: 0x00000001cca063a0 SwiftUI`___lldb_unnamed_symbol158636 frame #11: 0x00000001cca09268 SwiftUI`___lldb_unnamed_symbol158726
5
3
505
Oct ’24
Opening file from main bundle in Xcode 16
I've just upgraded to Xcode 16 and my app now fails when attempting to read a text file from the main bundle. It finds the path but can't open the file so this snippet prints: "File read error for path: /private/var/containers/Bundle/Application/AABAD428-96BC-4B34-80B4-97FA80B77E58/Test.app/csvfile.csv" This worked fine up to 15.4. Has something changed? Thanks. class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let bundle = Bundle.main let path = bundle.path(forResource: "csvfile", ofType: "csv")! do { let content = try String(contentsOfFile: path, encoding: String.Encoding.ascii) } catch { print("File read error for path: \(String(describing: path))") } } }
5
0
396
Oct ’24
How do you create an actor with a non-sendable member variable that is initialized with async init()?
Here is my code: ` // A 3rd-party class I must use. class MySession{ init() async throws { // .. } } actor SessionManager{ private var mySession: MySession? // The MySession is not Sendable func createSession() async { do { mySession = try await MySession() log("getOrCreateSession() End, success.") } catch { log("getOrCreateSession() End, failure.") } } }` I get this warning: "Non-sendable type 'MySession' returned by implicitly asynchronous call to a nonisolated function cannot cross the actor boundary." How can this be fixed?
1
0
281
Oct ’24
Memory leaks caused by closures
Hi there, this is my first time posting here. I've heard that some of the apple developers are usually active on these forums, so I've decided to shoot my shot, because this question was driving me crazy for a few days now and nobody could yet give me a clear view on what's actually happening. Here is the first snippet of the code class Animal { var name = "Fischer" var command: () -> Void = { } deinit { print(#function, #line) } } do { var pet: Animal? = Animal() pet?.command = { print(pet?.name ?? "Bobby") } } This code causes a memory leak, because Reference 'pet' is created. Independent copy of the reference 'pet' is created inside the closure. now there are two references to the same object, which are 'pet' outside the closure and 'pet' inside the closure. As we exit the 'do' scope, the 'pet' reference is deleted, but ARC does not deallocate the object due to the strong reference 'pet', that is still referencing to the same object. And all of that causes a memory leak. Now here is the code, that is pretty similar, except for the fact, that we assign a nil to the 'pet' reference class Animal { var name = "Fischer" var command: () -> Void = { } deinit { print(#function, #line) } } do { var pet: Animal? = Animal() pet?.command = { print(pet?.name ?? "Bobby") } pet = nil } And boom! deinit is called, meaning that the object was deallocated, but how? Why was the object deallocated? If we are deleting the exact same reference, that was deleted by the end of the 'do' scope in the first snippet? Am I misunderstanding something? I really hope this post will find the right people, since I could not even find appropriate tags for that.
4
0
337
Oct ’24
Under Swift 6 on Sequoia, why is ContiguousArray suddenly so slow to allocate
I generate images with command line apps in Swift on MacOS. Under the prior Xcode/MacOS my code had been running at the same performance for years. Converting to Swift 6 (no code changes) and running on Sequoia, I noticed a massive slowdown. Running Profile, I tracked it down to allow single line: var values = ContiguousArray<Double>(repeating: 0.0, count: localData.options.count) count for my current test case is 4, so its allocating 4 doubles at a time, around 40,000 times in this test. This one line takes 42 seconds out of a run time of 52 seconds. With the profile shown as: 26 41.62 s  4.8% 26.00 ms specialized ContiguousArray.init(_uninitializedCount:) 42 41.57 s  4.8% 42.00 ms _ContiguousArrayBuffer.init(_uninitializedCount:minimumCapacity:) 40730 40.93 s  4.7% 40.73 s _swift_allocObject_ 68 68.00 ms  0.0% 68.00 ms std::__1::pair<MallocTypeCacheEntry*, unsigned int> swift::ConcurrentReadableHashMap<MallocTypeCacheEntry, swift::LazyMutex>::find<unsigned int>(unsigned int const&, swift::ConcurrentReadableHashMap<MallocTypeCacheEntry, swift::LazyMutex>::IndexStorage, unsigned long, MallocTypeCacheEntry*) 7 130.00 ms  0.0% 7.00 ms swift::swift_slowAllocTyped(unsigned long, unsigned long, unsigned long long) which is clearly inside the OS allocator somewhere. What happened? Previously this would have taken closer to 8 seconds or so for the entire run.
3
0
304
Oct ’24
Symbol not found: _swift_getTypeByMangledNameInContext2
We have MacOS application which uses Network Extensions. When building it with XCode 15 and 15.0.1 the extension crashes on Intel based Macs with the following error: Symbol not found: _swift_getTypeByMangledNameInContext2 Expected in: /usr/lib/swift/libswiftCore.dylib We tested it on Big Sur and Ventura with the same outcome. On Ventura when running on Intel based Mac libswiftCore.dylib really doesn't provide this symbol: nm -g libswiftCore.dylib | grep Mangle 00007ff80faf6150 T _$ss031_getFunctionFullNameFromMangledD007mangledD0SSSgSS_tF 00007ff80fcc4460 T _swift_getFunctionFullNameFromMangledName 00007ff80fcc40b0 T _swift_getMangledTypeName 00007ff80fcf7ed0 T _swift_getTypeByMangledName 00007ff80fcf8230 T _swift_getTypeByMangledNameInContext 00007ff80fcf8370 T _swift_getTypeByMangledNameInContextInMetadataState 00007ff80fcf7d90 T _swift_getTypeByMangledNameInEnvironment 00007ff80fcf80f0 T _swift_getTypeByMangledNameInEnvironmentInMetadataState 00007ff80fcfb460 T _swift_getTypeByMangledNode Is there any workaround for this issue? Crash log is the following: Thread 0 Crashed:: Dispatch queue: com.apple.main-thread 0 dyld 0x000000010a165f7a __abort_with_payload + 10 1 dyld 0x000000010a18ef40 abort_with_payload_wrapper_internal + 80 2 dyld 0x000000010a18ef72 abort_with_payload + 9 3 dyld 0x000000010a10f14a dyld::halt(char const*) + 672 4 dyld 0x000000010a10f274 dyld::fastBindLazySymbol(ImageLoader**, unsigned long) + 167 5 libdyld.dylib 0x00007fff203b3376 dyld_stub_binder + 282 6 ??? 0x0000000104b086a0 0 + 4373644960 7 com.xxxx.Tunnel 0x00000001049d318a 0x10489e000 + 1266058 8 com.xxxx.Tunnel 0x00000001049df35d 0x10489e000 + 1315677 9 com.xxxx.Tunnel 0x00000001048a0765 0x10489e000 + 10085 10 com.apple.ExtensionKit 0x00007fff31bda683 __112-[EXConcreteExtensionContextVendor _beginRequestWithExtensionItems:listenerEndpoint:withContextUUID:completion:]_block_invoke + 808 11 libdispatch.dylib 0x00007fff201ec5dd _dispatch_call_block_and_release + 12 12 libdispatch.dylib 0x00007fff201ed7c7 _dispatch_client_callout + 8 13 libdispatch.dylib 0x00007fff201f9b86 _dispatch_main_queue_callback_4CF + 940 14 com.apple.CoreFoundation 0x00007fff204ce356 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 9 15 com.apple.CoreFoundation 0x00007fff20490188 __CFRunLoopRun + 2745 16 com.apple.CoreFoundation 0x00007fff2048efe2 CFRunLoopRunSpecific + 567 17 com.apple.Foundation 0x00007fff21151fa1 -[NSRunLoop(NSRunLoop) runMode:beforeDate:] + 212 18 com.apple.Foundation 0x00007fff211e0384 -[NSRunLoop(NSRunLoop) run] + 76 19 libxpc.dylib 0x00007fff200e53dd _xpc_objc_main + 825 20 libxpc.dylib 0x00007fff200e4e65 xpc_main + 437 21 com.apple.Foundation 0x00007fff211732bd -[NSXPCListener resume] + 262 22 com.apple.pluginkit.framework 0x00007fff2b288273 0x7fff2b26d000 + 111219 23 com.apple.pluginkit.framework 0x00007fff2b287efb 0x7fff2b26d000 + 110331 24 com.apple.pluginkit.framework 0x00007fff2b288639 0x7fff2b26d000 + 112185 25 com.apple.ExtensionKit 0x00007fff31be6d05 EXExtensionMain + 70 26 com.apple.Foundation 0x00007fff211e2479 NSExtensionMain + 208 27 libdyld.dylib 0x00007fff203b4621 start + 1
4
0
978
Dec ’23
Command SwiftCompile failed with a nonzero exit code. in xocde 16 and 15 where as it was working fine in xcode 14.3
My project’s source code was building, running, and archiving successfully in Xcode 14.3. However, after upgrading to Xcode 15, I began encountering the error: “Command SwiftCompile failed with a nonzero exit code.” I couldn't resolve the issue, so I decided to continue using Xcode 14.3. Recently, I upgraded to macOS Sequoia and also updated to Xcode 16. Unfortunately, the same error persists in the latest Xcode: “Command SwiftCompile failed with a nonzero exit code.” The unfortunate part is that Xcode 14.3 no longer works after the macOS upgrade. Whenever I try to run the code, I get the following popup.
10
0
878
Sep ’24
Can i use c++ in swift app project
Can i use c++ library with c library in swift app project Hello. I want to use a C++ library in my Swift app project. First, our company has an internal solution library. When built, it generates a Static Library in '.a' format, and we use it by connecting the library's Header to the App_Bridging_Header. There's no problem with this part. However, the new feature now includes C++. It also generates a Static Library in '.a' format. So, I tried to use the same method and created an App_Bridging_Header. But an error occurs, and I can't proceed. The first error occurs in the library file: 'iostream' file not found The second error occurs in the App_Bridging_Header: failed to emit precompiled header '/Users/kimjitae/Library/Developer/Xcode/DerivedData/ddddd-glmnoqrwdrgarrhjulxjmalpyikr/Build/Intermediates.noindex/PrecompiledHeaders/ddddd-Bridging-Header-swift_3O89L0OXZ0CPD-clang_188AW1HK8F0Q3.pch' for bridging header '/Users/kimjitae/Desktop/enf4/ddddd/ddddd/ddddd-Bridging-Header.h' Our library is developed in C++ using Xcode, and there's no problem when we run and build just the library project. The build succeeds, and the '.a' file is generated correctly. However, when we try to connect it with the app, the above problems occur. Could there be a problem because we also need to use the existing C library alongside this? The build is successful in an app project created with Objective-C.
4
0
259
Oct ’24
Casting `[String: Any]` to `[String: any Sendable]`
I have a simple wrapper class around WCSession to allow for easier unit testing. I'm trying to update it to Swift 6 concurrency standards, but running into some issues. One of them is in the sendMessage function (docs here It takes [String: Any] as a param, and returns them as the reply. Here's my code that calls this: @discardableResult public func sendMessage(_ message: [String: Any]) async throws -&gt; [String: Any] { return try await withCheckedThrowingContinuation { (continuation: CheckedContinuation&lt;[String: Any], Error&gt;) in wcSession.sendMessage(message) { response in continuation.resume(returning: response) // ERROR HERE } errorHandler: { error in continuation.resume(throwing: error) } } } However, I get this error: Sending 'response' risks causing data races; this is an error in the Swift 6 language mode Which I think is because Any is not Sendable. I tried casting [String: Any] to [String: any Sendable] but then it says: Conditional cast from '[String : Any]' to '[String : any Sendable]' always succeeds Any ideas on how to get this to work?
3
1
377
Oct ’24
Swift Testing not recognising tests
For my app I was trying to write some tests to ensure the functionality of all features. As I am using Xcode 16.0 I thought I might use Swift testing which was newly introduced and replaces XCTest. I created a new test target with Swift Testing and tried to run the first test, which was created automatically by the system. struct FinancialTests { @Test func testExample() async throws { #expect(true) } } Xcode is also showing the test diamond next to the function so I clicked on it to execute it. The app started to build and the build ended successfully. The the next step was testing. And after waiting for 10 minutes or so, no test was executed. First I thought maybe the test was not found, but in the test case overview all tests were shown: The run only shows this: Can someone help me to get this running. Many thanks!
3
1
333
Sep ’24
Can't link Obj-C Enum Symbol with DocC
Hi all, I am trying to use this guide to link directly to symbols in my documentation. But I am unable to get it to link to an Objective-C enum case. For example ``EnumNameType/EnumNameMyCase`` does not create a link. It works fine for method names, etc. I have tried all of the combinations I can think of, but I can't get it to work. Any help is much appreciated!
3
0
301
Oct ’24
Crash with Incorrect actor executor assumption
I'm seeing a crash compiling with Swift 6 that I can reproduce with the following code. It crashes with "Incorrect actor executor assumption". Is there something that the compiler should be warning about so that this isn't a runtime crash? Note - if I use a for in loop instead of the .forEach closure, the crash does not happen. Is the compiler somehow inferring the wrong isolation domain for the closure? import SwiftUI struct ContentView: View { var body: some View { Text("Hello, world!") .task { _ = try? await MyActor(store: MyStore()) } } } actor MyActor { var credentials = [String]() init(store: MyStore) async throws { try await store.persisted.forEach { credentials.append($0) } } } final class MyStore: Sendable { var persisted: [String] { get async throws { return ["abc"] } } } The stack trace is: * thread #6, queue = 'com.apple.root.user-initiated-qos.cooperative', stop reason = signal SIGABRT frame #0: 0x0000000101988f30 libsystem_kernel.dylib`__pthread_kill + 8 frame #1: 0x0000000100e2f124 libsystem_pthread.dylib`pthread_kill + 256 frame #2: 0x000000018016c4ec libsystem_c.dylib`abort + 104 frame #3: 0x00000002444c944c libswift_Concurrency.dylib`swift::swift_Concurrency_fatalErrorv(unsigned int, char const*, char*) + 28 frame #4: 0x00000002444c9468 libswift_Concurrency.dylib`swift::swift_Concurrency_fatalError(unsigned int, char const*, ...) + 28 frame #5: 0x00000002444c90e0 libswift_Concurrency.dylib`swift_task_checkIsolated + 152 frame #6: 0x00000002444c63e0 libswift_Concurrency.dylib`swift_task_isCurrentExecutorImpl(swift::SerialExecutorRef) + 284 frame #7: 0x0000000100d58944 IncorrectActorExecutorAssumption.debug.dylib`closure #1 in MyActor.init($0="abc") at <stdin>:0 frame #8: 0x0000000100d58b94 IncorrectActorExecutorAssumption.debug.dylib`partial apply for closure #1 in MyActor.init(store:) at <compiler-generated>:0 frame #9: 0x00000001947f8c80 libswiftCore.dylib`Swift.Sequence.forEach((τ_0_0.Element) throws -> ()) throws -> () + 428 * frame #10: 0x0000000100d58748 IncorrectActorExecutorAssumption.debug.dylib`MyActor.init(store=0x0000600000010ba0) at ContentView.swift:27:35 frame #11: 0x0000000100d57734 IncorrectActorExecutorAssumption.debug.dylib`closure #1 in ContentView.body.getter at ContentView.swift:14:32 frame #12: 0x0000000100d57734 IncorrectActorExecutorAssumption.debug.dylib`closure #1 in ContentView.body.getter at ContentView.swift:14:32 frame #13: 0x00000001d1817138 SwiftUI`(1) await resume partial function for partial apply forwarder for closure #1 () async -> () in closure #1 (inout Swift.TaskGroup<()>) async -> () in closure #1 () async -> () in SwiftUI.AppDelegate.application(_: __C.UIApplication, handleEventsForBackgroundURLSession: Swift.String, completionHandler: () -> ()) -> () frame #14: 0x00000001d17b1e48 SwiftUI`(1) await resume partial function for dispatch thunk of static SwiftUI.PreviewModifier.makeSharedContext() async throws -> τ_0_0.Context frame #15: 0x00000001d19c10c0 SwiftUI`(1) await resume partial function for generic specialization <()> of reabstraction thunk helper <τ_0_0 where τ_0_0: Swift.Sendable> from @escaping @isolated(any) @callee_guaranteed @async () -> (@out τ_0_0) to @escaping @callee_guaranteed @async () -> (@out τ_0_0, @error @owned Swift.Error) frame #16: 0x00000001d17b1e48 SwiftUI`(1) await resume partial function for dispatch thunk of static SwiftUI.PreviewModifier.makeSharedContext() async throws -> τ_0_0.Context
2
0
538
Oct ’24