Dive into the world of programming languages used for app development.

All subtopics

Post

Replies

Boosts

Views

Activity

Missing libclang_rt.osx.a library on OSX
I tried to install the flang-new compiler from Homebrew on Sequoia OSX. Complex division is broken because file divdc3 is missing. This file comes from libclang_rt.osx.a, a standard LLVM library. This library is missing on OSX. program test integer, parameter :: n=2 complex(kind=8), dimension(n,n) :: V complex(kind=8) :: PER V(1,1)=cmplx(4.0,2.0) V(2,2)=cmplx(5.0,3.0) V(1,2)=0.0 V(2,1)=0.5 PER=cmplx(1.2,1.2) V(:,:)=V(:,:)/PER end program test alainhebert@Alains-MacBook-Air-2 test_complex % flang-new test.f90 Undefined symbols for architecture arm64: “___divdc3”, referenced from: __QQmain in test-fc2bb3.o ld: symbol(s) not found for architecture arm64 flang-new: error: linker command failed with exit code 1 (use -v to see invocation)
1
0
131
1w
TaskExecutor and Swift 6 question
I have the following TaskExecutor code in Swift 6 and is getting the following error: //Error Passing closure as a sending parameter risks causing data races between main actor-isolated code and concurrent execution of the closure. May I know what is the best way to approach this? This is the default code generated by Xcode when creating a Vision Pro App using Metal as the Immersive Renderer. Renderer @MainActor static func startRenderLoop(_ layerRenderer: LayerRenderer, appModel: AppModel) { Task(executorPreference: RendererTaskExecutor.shared) { //Error let renderer = Renderer(layerRenderer, appModel: appModel) await renderer.startARSession() await renderer.renderLoop() } } final class RendererTaskExecutor: TaskExecutor { private let queue = DispatchQueue(label: "RenderThreadQueue", qos: .userInteractive) func enqueue(_ job: UnownedJob) { queue.async { job.runSynchronously(on: self.asUnownedSerialExecutor()) } } func asUnownedSerialExecutor() -> UnownedTaskExecutor { return UnownedTaskExecutor(ordinary: self) } static let shared: RendererTaskExecutor = RendererTaskExecutor() }
1
0
151
2d
Strange values written in loop
I don't understand what's happening when I save values via a loop. I initialize an array with default values, then run a loop to assign calculated values to it. In the middle of the loop, I print values, then print values again after the loop is over. The array values sometimes change, even though nothing has been written between print calls (when they change, the values are equal the last value in the array, index 49). I made a test file which writes four types of values to an array: (1) A new class instance, (2) Calculation, (3) Variable, (4) Hard-code. Saving the same value gives different results between the different write methods: import Foundation let numElements : Int = 50 class CustomType{ var x : Double var y : Double init(x: Double = 1.23, y: Double = 2.34) { self.x = x self.y = y } } // Try this four different ways var array1 = [CustomType](repeating:CustomType(), count:numElements) var array2 = [CustomType](repeating:CustomType(), count:numElements) var array3 = [CustomType](repeating:CustomType(), count:numElements) var array4 = [CustomType](repeating:CustomType(), count:numElements) // Checking that defaults were written print("Pre: Point 1: (\(array1[44].x),\(array1[44].y))") print("Pre: Point 2: (\(array2[44].x),\(array2[44].y))") print("Pre: Point 3: (\(array3[44].x),\(array3[44].y))") print("Pre: Point 4: (\(array4[44].x),\(array4[44].y))") // --- Fix 1: Problem goes away if I uncomment this: // array1[44]=CustomType() // array2[44]=CustomType() // array3[44]=CustomType() // array4[44]=CustomType() // --- Fix 2: Or if you swap these two lines for the following line: // let index = 44 // do { for index in 0..<numElements{ let rads = Double(index) * 2 * Double.pi/Double(numElements) let sinrads = sin(rads), cosrads = cos(rads) // Four different ways to save to arrays array1[index] = CustomType(x:sin(rads),y:cos(rads)) array2[index].x = sin(rads) array2[index].y = cos(rads) array3[index].x = sinrads array3[index].y = cosrads array4[index].x = -0.684547105928689 array4[index].y = 0.7289686274214113 if(index==44){ print("\n== Printing results mid-loop at index 44 ==") print("During: index: \(index), Calculated Rads: \(rads)") print("During: Calculated Vals: (\(sin(rads)),\(cos(rads)))") print("During: Stored 'let' Vals: (\(sinrads),\(cosrads))") print("During: Point 1: (\(array1[44].x),\(array1[44].y))") print("During: Point 2: (\(array2[44].x),\(array2[44].y))") print("During: Point 3: (\(array3[44].x),\(array3[44].y))") print("During: Point 4: (\(array4[44].x),\(array4[44].y))") } } print("\n== Printing the same results after the loop ==") print("Post: Point 1: (\(array1[44].x),\(array1[44].y))") print("Post: Point 2: (\(array2[44].x),\(array2[44].y))") print("Post: Point 3: (\(array3[44].x),\(array3[44].y))") print("Post: Point 4: (\(array4[44].x),\(array4[44].y))") print("\n== Reverse-calculating results from a correct array (array 1) to get the for loop index ==") print("reverse index calculation 01: \( (atan2(array1[ 1].x,array1[ 1].y) + Double.pi * 0) * Double(numElements)/(2*Double.pi) )") print("reverse index calculation 44: \( (atan2(array1[44].x,array1[44].y) + Double.pi * 2) * Double(numElements)/(2*Double.pi) )") print("reverse index calculation 45: \( (atan2(array1[45].x,array1[45].y) + Double.pi * 2) * Double(numElements)/(2*Double.pi) )") print("\n== Reverse-calculating results from an incorrect array (array 2) to get the for loop index ==") print("reverse index calculation 1: \( (atan2(array2[ 1].x,array2[ 1].y) + Double.pi * 2) * Double(numElements)/(2*Double.pi) )") print("reverse index calculation 44: \( (atan2(array2[44].x,array2[44].y) + Double.pi * 2) * Double(numElements)/(2*Double.pi) )") print("reverse index calculation 45: \( (atan2(array2[45].x,array2[45].y) + Double.pi * 2) * Double(numElements)/(2*Double.pi) )") Which gives the following output: Pre: Point 1: (1.23,2.34) Pre: Point 2: (1.23,2.34) Pre: Point 3: (1.23,2.34) Pre: Point 4: (1.23,2.34) == Printing results mid-loop at index 44 == During: index: 44, Calculated Rads: 5.529203070318036 During: Calculated Vals: (-0.684547105928689,0.7289686274214113) During: Stored 'let' Vals: (-0.684547105928689,0.7289686274214113) During: Point 1: (-0.684547105928689,0.7289686274214113) During: Point 2: (-0.684547105928689,0.7289686274214113) During: Point 3: (-0.684547105928689,0.7289686274214113) During: Point 4: (-0.684547105928689,0.7289686274214113) == Printing the same results after the loop == Post: Point 1: (-0.684547105928689,0.7289686274214113) Post: Point 2: (-0.12533323356430465,0.9921147013144778) Post: Point 3: (-0.12533323356430465,0.9921147013144778) Post: Point 4: (-0.684547105928689,0.7289686274214113) == Reverse-calculating results from a correct array (array 1) to get the for loop index == reverse index calculation 01: 1.0000000000000002 reverse index calculation 44: 43.99999999999999 reverse index calculation 45: 45.0 == Reverse-calculating results from an incorrect array (array 2) to get the for loop index == reverse index calculation 1: 49.0 reverse index calculation 44: 49.0 reverse index calculation 45: 49.0 Program ended with exit code: 0 Re-initializing the objects prior to the loop fixes the problem (see "Fix 1" in the comments), but the elements of the array are all initialized during creation and I don't understand why doing it a second time is helpful. The values should all be the same, am I missing something simple?
1
0
172
3d
Cast Any to Sendable
I'm continuing with the migration towards Swift 6. Within one of our libraries, I want to check whether a parameter object: Any? confirms to Sendable. I tried the most obvious one: if let sendable = object as? Sendable { } But that results into the compiler error "Marker protocol 'Sendable' cannot be used in a conditional cast". Is there an other way to do this?
3
0
665
Jul ’24
@Observable class not compatible with Codable?
So any time I create a class that's both @Observable and Codable, e.g. @Observable class GameLocationManager : Codable { I get a warning in the macro expansion code: @ObservationIgnored private let _$observationRegistrar = Observation.ObservationRegistrar() Immutable property will not be decoded because it is declared with an initial value which cannot be overwritten. I've been ignoring them for now, but there are at least a half a dozen of them now in my (relatively small) codebase, and I'd like to find a solution (ideally one that doesn't require me to write init(decoder:) for every @Observable class in my project...), especially since I'm not sure what the actual consequences of ignoring this might be.
2
0
469
Jul ’24
Label cannot export localized string key
Hello all. This is my code snippet. RecordListView() .tabItem { Label("Record List", systemImage: "list.clipboard") } .tag(Tab.RecordList) When I export localizations, there is no Record List in the .xcloc file. Then I use LocalizedStringKey for Label and export localizations file, the code is as follows: let RecordsString:LocalizedStringKey = "Tab.Records" RecordListView() .tabItem { Label(RecordsString, systemImage: "list.clipboard") } .tag(Tab.RecordList) There is still no Tab.Records.
2
0
286
2w
Token is not a valid binary operator in a preprocessor subexpression
I have a relatively unique project layered with file types (top to bottom) SwiftUI, Swift, Objective C, and C. The purpose of this layering is that I have a C language firmware application framework for development of firmware on custom electronic boards. Specifically, I use the standard C preprocessor in specific ways to make data driven structures, not code. There are header files shared between the firmware project and the Xcode iPhone app to set things like the BLE protocol and communication command/reply protocols, etc. The app is forced to adhere to that defined by the firmware, rather than rely a design to get it right. The Objective C code is mainly to utilize the Bluetooth stack provided by iOS. I specifically use this approach to allow C files to be compiled. Normally, everything has worked perfectly, but a serious and obtuse problem just surfaced a couple days ago. My important project was created long ago. More recently, I started a new project using most of the same technology, but its project is newer. Ironically, it continues to work perfectly, but ironically the older project stopped working. (Talking about the Xcode iOS side.) Essentially, the Objective C handling of the C preprocessor is not fully adhering to the standard C preprocessing in one project. It's very confusing because there is no code change. It seems Xcode was updated, but looks like the project was not updated, accordingly? I'm guessing there is some setting that forces Objective C to adhere to the standard C preprocessor rules. I did see a gnu compiler version that did not get updated compared to the newer project, but updating that in the Build Settings did not fix the problem. The error is in the title: Token is not a valid binary operator in a preprocessor subexpression. The offending macro appears in a header file, included in several implementation files. Compiling a single implementation files isolates the issue somewhat. An implementation with no Objective C objects compiles just fine. If there are Objective C objects then I get the errors. Both cases include the same header. It seems like the Objective C compiler, being invoked, uses a different C preprocessor parser, rather than the standard. I guess I should mention the bridging header file where these headers exist, as well. The offending header with the problem macro appears as an error in the bridging header if a full build is initiated. Is there an option somewhere, that forces the Objective C compiler to honor the standard C processor? Note, one project seems to. #define BLE_SERVICE_BLANK( enumTag, uuid, serviceType ) #define BLE_CHARACTERISTIC_BLANK( enumTag, uuid, properties, readPerm, writePerm, value) #define BLE_SERVICE_ENUM_COUNTER( enumTag, uuid, serviceType) +1 #define BLE_CHARACTERISTIC_ENUM_COUNTER( enumTag, uuid, properties, readPerm, writePerm, value) +1 #if 0 BLE_SERVICE_LIST(BLE_SERVICE_ENUM_COUNTER, BLE_CHARACTERISTIC_BLANK) &gt; 0 #define USING_BLE_SERVICE ... #if 0 BLE_SERVICE_LIST(BLE_SERVICE_BLANK, BLE_CHARACTERISTIC_ENUM_COUNTER) &gt; 0 #define USING_BLE_CHARACTERISTIC ... token is not a valid binary operator in a preprocessor subexpression refers to the comparison. BLE_SERVICE_LIST() does a +1 for each item in the list. There is no further expansion. One counts services. The other counts characteristics. The errors are associated with the comparisons.
8
0
329
4w
MultiThreaded rendering with actor
Hi, I'm trying to modify the ScreenCaptureKit Sample code by implementing an actor for Metal rendering, but I'm experiencing issues with frame rendering sequence. My app workflow is: ScreenCapture -&gt; createFrame -&gt; setRenderData Metal draw callback -&gt; renderAsync (getData from renderData) I've added timestamps to verify frame ordering, I also using binarySearch to insert the frame with timestamp, and while the timestamps appear to be in sequence, the actual rendering output seems out of order. // ScreenCaptureKit sample func createFrame(for sampleBuffer: CMSampleBuffer) async { if let surface: IOSurface = getIOSurface(for: sampleBuffer) { await renderer.setRenderData(surface, timeStamp: sampleBuffer.presentationTimeStamp.seconds) } } class Renderer { ... func setRenderData(surface: IOSurface, timeStamp: Double) async { _ = await renderSemaphore.getSetBuffers( isGet: false, surface: surface, timeStamp: timeStamp ) } func draw(in view: MTKView) { Task { await renderAsync(view) } } func renderAsync(_ view: MTKView) async { guard await renderSemaphore.beginRender() else { return } guard let frame = await renderSemaphore.getSetBuffers( isGet: true, surface: nil, timeStamp: nil ) else { await renderSemaphore.endRender() return } guard let texture = await renderSemaphore.getRenderData( device: self.device, surface: frame.surface) else { await renderSemaphore.endRender() return } guard let commandBuffer = _commandQueue.makeCommandBuffer(), let renderPassDescriptor = await view.currentRenderPassDescriptor, let renderEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: renderPassDescriptor) else { await renderSemaphore.endRender() return } // Shaders .. renderEncoder.endEncoding() commandBuffer.addCompletedHandler() { @Sendable (_ commandBuffer)-&gt; Swift.Void in updateFPS() } // commit frame in actor let success = await renderSemaphore.commitFrame( timeStamp: frame.timeStamp, commandBuffer: commandBuffer, drawable: view.currentDrawable! ) if !success { print("Frame dropped due to out-of-order timestamp") } await renderSemaphore.endRender() } } actor RenderSemaphore { private var frameBuffers: [FrameData] = [] private var lastReadTimeStamp: Double = 0.0 private var lastCommittedTimeStamp: Double = 0 private var activeTaskCount = 0 private var activeRenderCount = 0 private let maxTasks = 3 private var textureCache: CVMetalTextureCache? init() { } func initTextureCache(device: MTLDevice) { CVMetalTextureCacheCreate(kCFAllocatorDefault, nil, device, nil, &amp;self.textureCache) } func beginRender() -&gt; Bool { guard activeRenderCount &lt; maxTasks else { return false } activeRenderCount += 1 return true } func endRender() { if activeRenderCount &gt; 0 { activeRenderCount -= 1 } } func setTextureLoaded(_ loaded: Bool) { isTextureLoaded = loaded } func getSetBuffers(isGet: Bool, surface: IOSurface?, timeStamp: Double?) -&gt; FrameData? { if isGet { if !frameBuffers.isEmpty { let frame = frameBuffers.removeFirst() if frame.timeStamp &gt; lastReadTimeStamp { lastReadTimeStamp = frame.timeStamp print(frame.timeStamp) return frame } } return nil } else { // Set let frameData = FrameData( surface: surface!, timeStamp: timeStamp! ) // insert to the right position let insertIndex = binarySearch(for: timeStamp!) frameBuffers.insert(frameData, at: insertIndex) return frameData } } private func binarySearch(for timeStamp: Double) -&gt; Int { var left = 0 var right = frameBuffers.count while left &lt; right { let mid = (left + right) / 2 if frameBuffers[mid].timeStamp &gt; timeStamp { right = mid } else { left = mid + 1 } } return left } // for setRenderDataNormalized func tryEnterTask() -&gt; Bool { guard activeTaskCount &lt; maxTasks else { return false } activeTaskCount += 1 return true } func exitTask() { activeTaskCount -= 1 } func commitFrame(timeStamp: Double, commandBuffer: MTLCommandBuffer, drawable: MTLDrawable) async -&gt; Bool { guard timeStamp &gt; lastCommittedTimeStamp else { print("Drop frame at commit: \(timeStamp) &lt;= \(lastCommittedTimeStamp)") return false } commandBuffer.present(drawable) commandBuffer.commit() lastCommittedTimeStamp = timeStamp return true } func getRenderData( device: MTLDevice, surface: IOSurface, depthData: [Float] ) -&gt; (MTLTexture, MTLBuffer)? { let _textureName = "RenderData" var px: Unmanaged&lt;CVPixelBuffer&gt;? let status = CVPixelBufferCreateWithIOSurface(kCFAllocatorDefault, surface, nil, &amp;px) guard status == kCVReturnSuccess, let screenImage = px?.takeRetainedValue() else { return nil } CVMetalTextureCacheFlush(textureCache!, 0) var texture: CVMetalTexture? = nil let width = CVPixelBufferGetWidthOfPlane(screenImage, 0) let height = CVPixelBufferGetHeightOfPlane(screenImage, 0) let result2 = CVMetalTextureCacheCreateTextureFromImage( kCFAllocatorDefault, self.textureCache!, screenImage, nil, MTLPixelFormat.bgra8Unorm, width, height, 0, &amp;texture) guard result2 == kCVReturnSuccess, let cvTexture = texture, let mtlTexture = CVMetalTextureGetTexture(cvTexture) else { return nil } mtlTexture.label = _textureName let depthBuffer = device.makeBuffer(bytes: depthData, length: depthData.count * MemoryLayout&lt;Float&gt;.stride)! return (mtlTexture, depthBuffer) } } Above's my code - could someone point out what might be wrong?
7
0
233
1w
Memory leak and a crash when swizzling NSURLRequest initialiser
When swizzling NSURLRequest initialiser and returning a mutable copy, the original instance does not get deallocated and eventually gets leaked and a crash follows after that. Here's the swizzling setup: static func swizzleInit() { let initSel = NSSelectorFromString("initWithURL:cachePolicy:timeoutInterval:") guard let initMethod = class_getInstanceMethod(NSClassFromString("NSURLRequest"), initSel) else { return } let origInitImp = method_getImplementation(initMethod) let block: @convention(block) (AnyObject, Any, NSURLRequest.CachePolicy, TimeInterval) -> NSURLRequest = { _self, url, policy, interval in typealias OrigInit = @convention(c) (AnyObject, Selector, Any, NSURLRequest.CachePolicy, TimeInterval) -> NSURLRequest let origFunc = unsafeBitCast(origInitImp, to: OrigInit.self) let request = origFunc(_self, initSel, url, policy, interval) return request.tagged() } let newImplementation = imp_implementationWithBlock(block as Any) method_setImplementation(initMethod, newImplementation) } // create a mutable copy if needed and add a header private func tagged() -> NSURLRequest { guard let mutableRequest = self as? NSMutableURLRequest ?? self.mutableCopy() as? NSMutableURLRequest else { return self } mutableRequest.setValue("test", forHTTPHeaderField: "test") return mutableRequest } Then, we have a few test cases: // memory leak and crash func testSwizzleNSURLRequestInit() { let request = NSURLRequest(url: URL(string: "https://example.com")!) XCTAssertEqual(request.value(forHTTPHeaderField: "test"), "test") } // no crash, as the request is mutable, so no copy is created func testSwizzleNSURLRequestInit2() { let request = URLRequest(url: URL(string: "https://example.com")!) XCTAssertEqual(request.value(forHTTPHeaderField: "test"), "test") } // no crash, as the request is mutable, so no copy is created func testSwizzleNSURLRequestInit3() { let request = NSMutableURLRequest(url: URL(string: "https://example.com")!) XCTAssertEqual(request.value(forHTTPHeaderField: "test"), "test") } // no crash, as the new instance does not get deallocated // when the test method completes (?) var request: NSURLRequest? func testSwizzleNSURLRequestInit4() { request = NSURLRequest(url: URL(string: "https://example.com")!) XCTAssertEqual(request?.value(forHTTPHeaderField: "test"), "test") } It appears a memory leak occurs only when any other instance except for the original one is being returned from the initialiser. Is there a workaround to prevent the leak, while allowing for modifications of all requests?
3
0
305
Oct ’24
Using metal-cpp with Swift
Is there any way to use metal-cpp in a Swift project? I have a platform layer I've written in Swift that handles Window/View creation, as well as event handling, etc. I've been trying to bridge this layer with my C++ layer as you normally would using a pure C interface, but using Metal instances that cross this boundary just doesn't seem to work. e.g. Currently I initialize a CAMetalLayer for my NSView, setting that as the layer for the view. I've tried passing this Metal layer into my C++ code via a void* pointer through a C interface, and then casting it to a CA::MetalView to be used. When this didn't work, I tried creating the CA::MetalLayer in C++ and passing that back to the Swift layer as a void* pointer, then binding it to a CAMetalLayer type. And of course, this didn't work either. So are the options for metal-cpp to use either Objective-C or just pure C++ (using AppKit.hpp)? Or am I missing something for how to integrate with Swift?
1
0
940
Sep ’23
How swift string is internally managing memory ?
When i create a intance of swift String : Let str = String ("Hello") As swift String are immutable, and when we mutate the value of these like: str = "Hello world ......." // 200 characters Swift should internally allocate new memory and copy the content to that buffer for update . But when i checked the addresses of original and modified str, both are same? Can you help me understand how this allocation and mutation working internally in swift String?
1
0
166
1w
Entering debugger: Cannot create Swift scratch context (couldn't create a ClangImporter)
similiar to Error when debugging: Cannot creat… | Apple Developer Forums - https://developer.apple.com/forums/thread/651375 Xcode 12 beta 1 po command in de… | Apple Developer Forums - https://developer.apple.com/forums/thread/651157 which do not resolve this issue that I am encountering Description of problem I am seeing an error which prevents using lldb debugger on Swift code/projects. It is seen on any Swift or SwiftUI project that I've tried. This is the error displayed in lldb console when first breakpoint is encountered: Cannot create Swift scratch context (couldn't create a ClangImporter)(lldb)  Xcode Version 12.3 (12C33) macOS Big Sur Intel M1 Troubleshooting I originally thought this was also working on an Intel Mac running Big Sur/Xcode 12.3, but was mistaken. Using my customized shell environment on the following setups, I encounter the same couldn't create a ClangImporter. M1 Mac mini, main account (an "Admin" account) same M1 Mac mini, new "dev" account (an "Admin" account) Intel MBP, main account They are all using an Intel Homebrew install, and my customized shell environment if that provides a clue? I captured some lldb debugging info by putting expr types in ~/.lldbinit but the outputs were basically identical (when discounting scratch file paaths and memory addresses) compared to the "working clean" account log (described below) log enable -f /tmp/lldb-log.txt lldb expr types works in a "clean" user account I created a new, uncustomized "Standard" testuser account on the M1 Mac mini, and launched the same system Xcode.app. There was no longer this error message, and was able to inspect variables at a swift program breakpoint in Swift context, including po symbol. Impact Effectively this makes the debugger in Swift on Xcode projects on my systems essentially unable to inspect Swift contexts' state.
6
0
4.9k
Jan ’21
using Swift Library from c++ code - calllbacks ?
Hello, Im developing an app entirely with C++, and I need to call various swift functions because it requires the Swift library. Ive seen several posts on forums about C++ callbacks and honestly I dont understand how its done exactly. I get the general idea but I am not able to understand it and make it work. I feel like people throw vague ideas and weird function names and everything gets confusing. Could anyone give me the smallest example that works please ? Just to make sure you know what I mean, here is an example of what I want to do, but you dont have to generate the code exactly for this, I want an example that I can understand please, but the swift code has to depend on a swift library. I dont want to simply call a swift function that returns x*2 ... {1} notif.swift file : coded in swift language include <UserNotifications/UserNotifications.h> function A that show notification in swift code. {2} mainwindow.cpp file : coded in C++ language import notif.swift ?? button connected to slot/function mybuttonclicked. MainWindow::mybuttonclicked(){ std::string my_result = call function A_from_swift_file(argument_1); } --The end --- I wrote the notif.swift with '?' because I dont know how you include the swift file from your cpp code and I could not find that anywhere. Maybe it is obvious, but I would really appreciate getting some help on this, Thank you everyone
3
0
262
2w
unexpected nil
` init() { nextOrder = self.AllItems.map{$0.order}.max() if nextOrder == nil { nextOrder = 0 } nextOrder! += 1 // <--- Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value } ` I have to say, Swift is great - when it works!
8
0
353
2w
Potential of race condition in ARC?
I ran into a memory issue that I don't understand why this could happen. For me, It seems like ARC doesn't guarantee thread-safety. Let see the code below @propertyWrapper public struct AtomicCollection&lt;T&gt; { private var value: [T] private var lock = NSLock() public var wrappedValue: [T] { set { lock.lock() defer { lock.unlock() } value = newValue } get { lock.lock() defer { lock.unlock() } return value } } public init(wrappedValue: [T]) { self.value = wrappedValue } } final class CollectionTest: XCTestCase { func testExample() throws { let rounds = 10000 let exp = expectation(description: "test") exp.expectedFulfillmentCount = rounds @AtomicCollection var array: [Int] = [] for i in 0..&lt;rounds { DispatchQueue.global().async { array.append(i) exp.fulfill() } } wait(for: [exp]) } } It will crash for various reasons (see screenshots below) I know that the test doesn't reflect typical application usage. My app is quite different from traditional app so the code above is just the simplest form for proof of the issue. One more thing to mention here is that array.count won't be equal to 10,000 as expected (probably because of copy-on-write snapshot) So my questions are Is this a bug/undefined behavior/expected behavior of Swift/Obj-c ARC? Why this could happen? Any solutions suggest? How do you usually deal with thread-safe collection (array, dict, set)?
2
0
224
2w
How to break `while` loop and `deliver partial result to `View`?
I make some small program to make dots. Many of them. I have a Generator which generates dots in a loop: //reprat until all dots in frame while !newDots.isEmpty { virginDots = [] for newDot in newDots { autoreleasepool{ virginDots.append( contentsOf: newDot.addDots(in: size, allDots: &result, inSomeWay)) } newDots = virginDots } counter += 1 print ("\(result.count) dots in \(counter) grnerations") } Sometimes this loop needs hours/days to finish (depend of inSomeWay settings), so it would be very nice to send partial result to a View, and/or if result is not satisfying — break this loop and start over. My understanding of Tasks and Concurrency became worse each time I try to understand it, maybe it's my age, maybe language barier. For now, Button with {Task {...}} action doesn't removed Rainbow Wheel from my screen. Killing an app is wrong because killing is wrong. How to deal with it?
4
0
190
2w
Working correctly with actor annotated class
Hi, I have a complex structure of classes, and I'm trying to migrate to swift6 For this classes I've a facade that creates the classes for me without disclosing their internals, only conforming to a known protocol I think I've hit a hard wall in my knowledge of how the actors can exchange data between themselves. I've created a small piece of code that can trigger the error I've hit import SwiftUI import Observation @globalActor actor MyActor { static let shared: some Actor = MyActor() init() { } } @MyActor protocol ProtocolMyActor { var value: String { get } func set(value: String) } @MyActor func make(value: String) -> ProtocolMyActor { return ImplementationMyActor(value: value) } class ImplementationMyActor: ProtocolMyActor { private(set) var value: String init(value: String) { self.value = value } func set(value: String) { self.value = value } } @MainActor @Observable class ViewObserver { let implementation: ProtocolMyActor var value: String init() async { let implementation = await make(value: "Ciao") self.implementation = implementation self.value = await implementation.value } func set(value: String) { Task { await implementation.set(value: value) self.value = value } } } struct MyObservedView: View { @State var model: ViewObserver? var body: some View { if let model { Button("Loaded \(model.value)") { model.set(value: ["A", "B", "C"].randomElement()!) } } else { Text("Loading") .task { self.model = await ViewObserver() } } } } The error Non-sendable type 'any ProtocolMyActor' passed in implicitly asynchronous call to global actor 'MyActor'-isolated property 'value' cannot cross actor boundary Occurs in the init on the line "self.value = await implementation.value" I don't know which concurrency error happens... Yes the init is in the MainActor , but the ProtocolMyActor data can only be accessed in a MyActor queue, so no data races can happen... and each access in my ImplementationMyActor uses await, so I'm not reading or writing the object from a different actor, I just pass sendable values as parameter to a function of the object.. can anybody help me understand better this piece of concurrency problem? Thanks
1
0
221
2w
Swift Concurrency Proposal Index
Swift concurrency is an important part of my day-to-day job. I created the following document for an internal presentation, and I figured that it might be helpful for others. If you have questions or comments, put them in a new thread here on DevForums. Use the App & System Services > Processes & Concurrency topic area and tag it with both Swift and Concurrency. Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com" Swift Concurrency Proposal Index This post summarises the Swift Evolution proposals that went into the Swift concurrency design. It covers the proposal that are implemented in Swift 6.0, plus a few additional ones that aren’t currently available. The focus is here is the Swift Evolution proposals. For general information about Swift concurrency, see the documentation referenced by Concurrency Resources. Swift 6.0 The following Swift Evolution proposals form the basis of the Swift 6.0 concurrency design. SE-0176 Enforce Exclusive Access to Memory link: SE-0176 notes: This defines the “Law of Exclusivity”, a critical foundation for both serial and concurrent code. SE-0282 Clarify the Swift memory consistency model ⚛︎ link: SE-0282 notes: This defines Swift’s memory model, that is, the rules about what is and isn’t allowed when it comes to concurrent memory access. SE-0296 Async/await link: SE-0296 introduces: async functions, async, await SE-0297 Concurrency Interoperability with Objective-C link: SE-0297 notes: Specifies how Swift imports an Objective-C method with a completion handler as an async method. Explicitly allows @objc actors. SE-0298 Async/Await: Sequences link: SE-0298 introduces: AsyncSequence, for await syntax notes: This just defines the AsyncSequence protocol. For one concrete implementation of that protocol, see SE-0314. SE-0300 Continuations for interfacing async tasks with synchronous code link: SE-0300 introduces: CheckedContinuation, UnsafeContinuation notes: Use these to create an async function that wraps a legacy request-reply concurrency construct. SE-0302 Sendable and @Sendable closures link: SE-0302 introduces: Sendable, @Sendable closures, marker protocols SE-0304 Structured concurrency link: SE-0304 introduces: unstructured and structured concurrency, Task, cancellation, CancellationError, withTaskCancellationHandler(…), sleep(…), withTaskGroup(…), withThrowingTaskGroup(…) notes: For the async let syntax, see SE-0317. For more ways to sleep, see SE-0329 and SE-0374. For discarding task groups, see SE-0381. SE-0306 Actors link: SE-0306 introduces: actor syntax notes: For actor-isolated parameters and the nonisolated keyword, see SE-0313. For global actors, see SE-0316. For custom executors and the Actor protocol, see SE-0392. SE-0311 Task Local Values link: SE-0311 introduces: TaskLocal SE-0313 Improved control over actor isolation link: SE-0313 introduces: isolated parameters, nonisolated SE-0314 AsyncStream and AsyncThrowingStream link: SE-0314 introduces: AsyncStream, AsyncThrowingStream, onTermination notes: These are super helpful when you need to publish a legacy notification construct as an async stream. For a simpler API to create a stream, see SE-0388. SE-0316 Global actors link: SE-0316 introduces: GlobalActor, MainActor notes: This includes the @MainActor syntax for closures. SE-0317 async let bindings link: SE-0317 introduces: async let syntax SE-0323 Asynchronous Main Semantics link: SE-0323 SE-0327 On Actors and Initialization link: SE-0327 notes: For a proposal to allow access to non-sendable isolated state in a deinitialiser, see SE-0371. SE-0329 Clock, Instant, and Duration link: SE-0329 introduces: Clock, InstantProtocol, DurationProtocol, Duration, ContinuousClock, SuspendingClock notes: For another way to sleep, see SE-0374. SE-0331 Remove Sendable conformance from unsafe pointer types link: SE-0331 SE-0337 Incremental migration to concurrency checking link: SE-0337 introduces: @preconcurrency, explicit unavailability of Sendable notes: This introduces @preconcurrency on declarations, on imports, and on Sendable protocols. For @preconcurrency conformances, see SE-0423. SE-0338 Clarify the Execution of Non-Actor-Isolated Async Functions link: SE-0338 note: This change has caught a bunch of folks by surprise and there’s a discussion underway as to whether to adjust it. SE-0340 Unavailable From Async Attribute link: SE-0340 introduces: noasync availability kind SE-0343 Concurrency in Top-level Code link: SE-0343 notes: For how strict concurrency applies to global variables, see SE-0412. SE-0374 Add sleep(for:) to Clock link: SE-0374 notes: This builds on SE-0329. SE-0381 DiscardingTaskGroups link: SE-0381 introduces: DiscardingTaskGroup, ThrowingDiscardingTaskGroup notes: Use this for task groups that can run indefinitely, for example, a network server. SE-0388 Convenience Async[Throwing]Stream.makeStream methods link: SE-0388 notes: This builds on SE-0314. SE-0392 Custom Actor Executors link: SE-0392 introduces: Actor protocol, Executor, SerialExecutor, ExecutorJob, assumeIsolated(…) Notes: For task executors, a closely related concept, see SE-0417. For custom isolation checking, see SE-0424. SE-0395 Observation link: SE-0395 introduces: Observation module, Observable notes: While this isn’t directly related to concurrency, it’s relationship to Combine, which is an important exising concurrency construct, means I’ve included it in this list. SE-0401 Remove Actor Isolation Inference caused by Property Wrappers link: SE-0401, commentary SE-0410 Low-Level Atomic Operations ⚛︎ link: SE-0410 introduces: Synchronization module, Atomic, AtomicLazyReference, WordPair SE-0411 Isolated default value expressions link: SE-0411, commentary SE-0412 Strict concurrency for global variables link: SE-0412 introduces: nonisolated(unsafe) notes: While this is a proposal about globals, the introduction of nonisolated(unsafe) applies to “any form of storage”. SE-0414 Region based Isolation link: SE-0414, commentary notes: To send parameters and results across isolation regions, see SE-0430. SE-0417 Task Executor Preference link: SE-0417, commentary introduces: withTaskExecutorPreference(…), TaskExecutor, globalConcurrentExecutor notes: This is closely related to the custom actor executors defined in SE-0392. SE-0418 Inferring Sendable for methods and key path literals link: SE-0418, commentary notes: The methods part of this is for “partial and unapplied methods”. SE-0420 Inheritance of actor isolation link: SE-0420, commentary introduces: #isolation, optional isolated parameters notes: This is what makes it possible to iterate over an async stream in an isolated async function. SE-0421 Generalize effect polymorphism for AsyncSequence and AsyncIteratorProtocol link: SE-0421, commentary notes: Previously AsyncSequence used an experimental mechanism to support throwing and non-throwing sequences. This moves it off that. Instead, it uses an extra Failure generic parameter and typed throws to achieve the same result. This allows it to finally support a primary associated type. Yay! SE-0423 Dynamic actor isolation enforcement from non-strict-concurrency contexts link: SE-0423, commentary introduces: @preconcurrency conformance notes: This adds a number of dynamic actor isolation checks (think assumeIsolated(…)) to close strict concurrency holes that arise when you interact with legacy code. SE-0424 Custom isolation checking for SerialExecutor link: SE-0424, commentary introduces: checkIsolation() notes: This extends the custom actor executors introduced in SE-0392 to support isolation checking. SE-0430 sending parameter and result values link: SE-0430, commentary introduces: sending notes: Adds the ability to send parameters and results between the isolation regions introduced by SE-0414. SE-0431 @isolated(any) Function Types link: SE-0431, commentary introduces: @isolated(any) attribute on function types, isolation property of functions values notes: This is laying the groundwork for SE-NNNN Closure isolation control. That, in turn, aims to bring the currently experimental @_inheritActorContext attribute into the language officially. SE-0433 Synchronous Mutual Exclusion Lock 🔒 link: SE-0433 introduces: Mutex SE-0434 Usability of global-actor-isolated types link: SE-0434, commentary notes: This loosen strict concurrency checking in a number of subtle ways. SE-0442 Allow TaskGroup's ChildTaskResult Type To Be Inferred link: SE-0442 notes: This represents a small quality of life improvement for withTaskGroup(…) and withThrowingTaskGroup(…). In Progress The proposals in this section didn’t make Swift 6.0. SE-0371 Isolated synchronous deinit link: SE-0371 availability: Swift 6.1 introduces: isolated deinit notes: Allows a deinitialiser to access non-sendable isolated state, lifting a restriction imposed by SE-0327. SE-0406 Backpressure support for AsyncStream link: SE-0406 availability: returned for revision notes: Currently AsyncStream has very limited buffering options. This was a proposal to improve that. This feature is still very much needed, but it’s not clear whether it’ll come back in anything resembling this guise. SE-0449 Allow nonisolated to prevent global actor inference link: SE-0449 availability: Swift 6.1 SE-NNNN Closure isolation control link: SE-NNNN introduces: @inheritsIsolation availability: not yet approved notes: This aims to bring the currently experimental @_inheritActorContext attribute into the language officially.
0
0
358
2w