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

All subtopics
Posts under Programming Languages topic

Post

Replies

Boosts

Views

Activity

Equatable with default actor isolation of MainActor
I filed the following issue on swiftlang/swift on GitHub (Aug 8th), and a followup the swift.org forums, but not getting any replies. As we near the release of Swift 6.2, I want to know if what I'm seeing below is expected, or if it's another case where the compiler needs a fix. protocol P1: Equatable { } struct S1: P1 { } // Error: Conformance of 'S1' to protocol 'P1' crosses into main actor-isolated code an can cause data races struct S1Workaround: @MainActor P1 { } // OK // Another potential workaround if `Equatable` conformance can be moved to the conforming type. protocol P2 { } struct S2: Equatable, P2 { } // OK There was a prior compiler bug fix which addressed inhereted protocols regarding @MainActor. For Equatable, one still has to use @MainActoreven when the default actor isolation is MainActor. Also affects Hashable and any other protocol inheriting from Equatable.
0
0
13
3h
Why is CKModifyRecordsOperation to batch delete records in CloudKit not deleting records?
My Code: let op = CKModifyRecordsOperation(recordIDsToDelete:recordIDsToDelete) op.modifyRecordsCompletionBlock = { _, deleteRecordIDs, error in if error == nil { print("successful delete deleteRecordIDS = \(deleteRecordIDs)") } else { print("delete error = \(error?.localizedDescription)") } } op.database = CKContainer.default().privateCloudDatabase op.qualityOfService = .userInitiated CKContainer.default().privateCloudDatabase.add(op) My problem is that CKRecord are not deleted once I reinstall the app: when I reinstall the app and try to delete a CloudKit record, the method is executed successfully (error is nil) but the records are still in CloudKit Dashboards.
1
0
51
8h
Location via GPS jumps
We have a that relies on accurate GPS location but we’ve noticed that every now and then the location ‘jumps’ a few hundred meters to a different location but reports horizonal accuracy less than 10m. we think the device is picking up a rough location from a local WiFi rather than internal gps sensors. can we a) disable WiFi location Updates? b) identify WiFi location Updates? thank You
1
0
56
9h
Function types as return types
func oneStepForward(_ input: Int) -> Int { return input + 1 } func oneStepBackward(_ input: Int) -> Int { return input - 1 } func chooseStepFunction(backward: Bool) -> (Int) -> Int { return backward ? oneStepBackward : oneStepForward //Error. type of expression is ambiguous without a type annotation } Why am I getting this error ? If I change this function to the following it works and will compile. func chooseStepFunction(backward: Bool) -> (Int) -> Int { if backward { return oneStepBackward } else { return oneStepForward } } // Why am I getting the error in the previous version while it works in the second version ? Thx in advance.
4
0
125
1d
Function types as return types
Greetings, func stepForward(_ input: Int) -> Int { return input + 1 } func stepBackward(_ input: Int) -> Int { return input - 1 } func chooseStepFunction(backward: Bool) -> (Int) -> Int { return backward ? stepBackward : stepForward /* Error type of expression is ambiguous without a type annotation */ } Why am I getting this error. If I change the function to func chooseStepFunction(backward: Bool) -> (Int) -> Int { if backward { return stepBackward else { return stepForward } } Why is the previous chooseStepFunction giving me an error ? Thx in advance
3
0
114
1d
ELEMENT_TYPE_OF_SET_VIOLATES_HASHABLE_REQUIREMENTS
Is this possible while inserting a String into Set Crashed: com.apple.root.user-initiated-qos.cooperative 0 libswiftCore.dylib 0xf4c0 _assertionFailure(_:_:flags:) + 136 1 libswiftCore.dylib 0x17f484 ELEMENT_TYPE_OF_SET_VIOLATES_HASHABLE_REQUIREMENTS(_:) + 3792 2 MyEatApp 0x44f6e8 specialized _NativeSet.insertNew(_:at:isUnique:) + 4333926120 (<compiler-generated>:4333926120) 3 MyEatApp 0x44eaec specialized Set._Variant.insert(_:) + 4333923052 (<compiler-generated>:4333923052) 4 MyEatApp 0x479f7c HomeViewModel.hanldeAnnouncementCard(from:) + 293 (HomeViewModel+PersonalizedOffer.swift:293) 5 libswift_Concurrency.dylib 0x5c134 swift::runJobInEstablishedExecutorContext(swift::Job*) + 292 6 libswift_Concurrency.dylib 0x5d5c8 swift_job_runImpl(swift::Job*, swift::SerialExecutorRef) + 156 7 libdispatch.dylib 0x13db0 _dispatch_root_queue_drain + 364 8 libdispatch.dylib 0x1454c _dispatch_worker_thread2 + 156 9 libsystem_pthread.dylib 0x9d0 _pthread_wqthread + 232 10 libsystem_pthread.dylib 0xaac start_wqthread + 8
6
0
272
4d
Overriding global new and delete is not working.
We developing Native App with C++17 for iOS. We override global new and delete operators. This App deallocate all allocated memories correctly by Run on Xcode (Command + R), but exception occurs launch from xcrun or App icon on iPhone. I debugged the exception. Overriding new operation was called correctly, but overriding delete operation was not called. The default delete was called. I'm not sure why is that. STEPS TO REPRODUCE Build xcode project. Run "xcrun devicectl device install app --device " Run "xcrun devicectl device process launch --console --device " PLATFORM AND VERSION iOS Development environment: Xcode 16.4, macOS macOS Sequoia 15.5 Run-time configuration: iOS 18.5 main.cpp I attached is sample code to reproduce this problem. main.cpp
4
0
578
1w
Swift 6 conversion for IBOutlet
I'm struggling to convert Swift 5 to Swift 6. As advised in doc, I first turned strict concurrency ON. I got no error. Then, selected swift6… and problems pop up. I have a UIViewController with IBOutlets: eg a TextField. computed var eg duree func using UNNotification: func userNotificationCenter I get the following error in the declaration line of the func userNotificationCenter: Main actor-isolated instance method 'userNotificationCenter(_:didReceive:withCompletionHandler:)' cannot be used to satisfy nonisolated requirement from protocol 'UNUserNotificationCenterDelegate' So, I declared the func as non isolated. This func calls another func func2, which I had also to declare non isolated. Then I get error on the computed var used in func2 Main actor-isolated property 'duree' can not be referenced from a nonisolated context So I declared duree as nonsilated(unsafe). Now comes the tricky part. The computed var references the IBOutlet dureeField if dureeField.text == "X" leading to the error Main actor-isolated property 'dureeField' can not be referenced from a nonisolated context So I finally declared the class as mainActor and the textField as nonisolated @IBOutlet nonisolated(unsafe) weak var dureeField : UITextField! That silences the error (but declaring unsafe means I get no extra robustness with swift6) just to create a new one when calling dureeField.text: Main actor-isolated property 'text' can not be referenced from a nonisolated context Question: how to address properties inside IBOutlets ? I do not see how to declare them non isolated and having to do it on each property of each IBOutlet would be impracticable. The following did work, but will make code very verbose: if MainActor.assumeIsolated({dureeField.text == "X"}) { So I must be missing something.
5
0
575
2w
Using Dynamic Member Lookup in a Superclass
As a fun project, I'm wanting to model an electronic circuit. Components inherit from a superclass (ElectronicComponent). Each subclass (e.g. Resistor) has certain methods to return properties (e.g. resistance), but may vary by the number of outlets (leads) they have, and what they are named. Each outlet connects to a Junction. In my code to assemble a circuit, while I'm able to manually hook up the outlets to the junctions, I'd like to be able to use code similar to the following… class Lead: Hashable // implementation omitted { let id = UUID() unowned let component: ElectronicComponent weak var connection: Junction? init(component: ElectronicComponent, to connection: Junction? = nil) { self.component = component self.connection = connection } } @dynamicMemberLookup class ElectronicComponent { let id = UUID() var connections: Set<Lead> = [] let label: String? init(label: String) { self.label = label } subscript<T>(dynamicMember keyPath: KeyPath<ElectronicComponent, T>) -> T { self[keyPath: keyPath] } func connect(lead: KeyPath<ElectronicComponent, Lead>, to junction: Junction) { let lead = self[keyPath: lead] lead.connection = junction connections.insert(lead) } } class Resistor: ElectronicComponent { var input, output: Lead? let resistance: Measurement<UnitElectricResistance> init(_ label: String, resistance: Measurement<UnitElectricResistance>) { self.resistance = resistance super.init(label: label) } } let resistorA = Resistor("R1", resistance: .init(value: 100, unit: .ohms)) let junctionA = Junction(name: "A") resistorA.connect(lead: \.outlet2, to: junctionA) While I'm able to do this by implementing @dynamicMemberLookup in each subclass, I'd like to be able to do this in the superclass to save repeating the code. subscript<T>(dynamicMember keyPath: KeyPath<ElectronicComponent, T>) -> T { self[keyPath: keyPath] } Unfortunately, the compiler is not allowing me to do this as the superclass doesn't know about the subclass properties, and at the call site, the subclass isn't seen as ElectronicComponent. I've been doing trial and error with protocol conformance and other things, but hitting walls each time. One possibility is replacing the set of outlets with a dictionary, and using Strings instead of key paths, but would prefer not to. Another thing I haven't tried is creating and adopting a protocol with the method implemented in there. Another considered approach is using macros in the subclasses, but I'd like to see if there is a possibility of achieving the goal using my current approach, for learning as much as anything.
6
0
325
2w
C++ and Swift in Xcode 16 broke my audio unit
I'm developing an audio unit for use on iOS. The AUv3 worked fine with xcode 15.X and swift 5.X. I recently tried to submit an update to my plug-in but Apple refused submission because my Xcode was not the latest. Now that I'm on Xcode 16.4 I can't get my project to compile, even when following all of the same previous steps. As one example of a change, Xcode doesn't appear to include the “C++ and Objective-C interoperability” build setting that it used to. This setting is noted in the Swift documentation and I used to need it, https://www.swift.org/documentation/cxx-interop/project-build-setup/#mixing-swift-and-c-using-xcode Currently my C++ code can't see anything from Swift, and I get a "Use of undeclared identifier 'project_name'". I've selected Switch support for version 5.0 in an attempt to minimize changes from Apple. My process is I generate an Xcode project file from my audio plugin support, JUCE. Then I add in the swift files, click yes to create bridging headers, but c++ doesn't see swift anymore. I'd greatly appreciate any suggestions.
3
0
273
2w
Compiler exception when using Binding and Swift 6
In my code I use a binding that use 2 methods to get and get a value. There is no problem with swift 5 but when I swift to swift 6 the compiler fails : Here a sample example of code to reproduce the problem : `import SwiftUI struct ContentView: View { @State private var isOn = false var body: some View { VStack { Image(systemName: "globe") .imageScale(.large) .foregroundStyle(.tint) Text("Hello, world!") Toggle("change it", isOn: Binding(get: getValue, set: setValue(_:))) } .padding() } private func getValue() -&gt; Bool { isOn } private func setValue(_ value: Bool) { isOn = value } }` Xcode compiler log error : 1. Apple Swift version 6.1.2 (swiftlang-6.1.2.1.2 clang-1700.0.13.5) 2. Compiling with the current language version 3. While evaluating request IRGenRequest(IR Generation for file "/Users/xavierrouet/Developer/TestCompilBindingSwift6/TestCompilBindingSwift6/ContentView.swift") 4. While emitting IR SIL function "@$sSbScA_pSgIeAghyg_SbIeAghn_TR". for &lt;&lt;debugloc at "&lt;compiler-generated&gt;":0:0&gt;&gt;Stack dump without symbol names (ensure you have llvm-symbolizer in your PATH or set the environment var LLVM_SYMBOLIZER_PATH` to point to it): 0 swift-frontend 0x000000010910ae24 llvm::sys::PrintStackTrace(llvm::raw_ostream&amp;, int) + 56 1 swift-frontend 0x0000000109108c5c llvm::sys::RunSignalHandlers() + 112 2 swift-frontend 0x000000010910b460 SignalHandler(int) + 360 3 libsystem_platform.dylib 0x0000000188e60624 _sigtramp + 56 4 libsystem_pthread.dylib 0x0000000188e2688c pthread_kill + 296 5 libsystem_c.dylib 0x0000000188d2fc60 abort + 124 6 swift-frontend 0x00000001032ff9a8 swift::DiagnosticHelper::~DiagnosticHelper() + 0 7 swift-frontend 0x000000010907a878 llvm::report_fatal_error(llvm::Twine const&amp;, bool) + 280 8 swift-frontend 0x00000001090aef6c report_at_maximum_capacity(unsigned long) + 0 9 swift-frontend 0x00000001090aec7c llvm::SmallVectorBase::grow_pod(void*, unsigned long, unsigned long) + 384 10 swift-frontend 0x000000010339c418 (anonymous namespace)::SyncCallEmission::setArgs(swift::irgen::Explosion&amp;, bool, swift::irgen::WitnessMetadata*) + 892 11 swift-frontend 0x00000001035f8104 (anonymous namespace)::IRGenSILFunction::visitFullApplySite(swift::FullApplySite) + 4792 12 swift-frontend 0x00000001035c876c (anonymous namespace)::IRGenSILFunction::visitSILBasicBlock(swift::SILBasicBlock*) + 2636 13 swift-frontend 0x00000001035c6614 (anonymous namespace)::IRGenSILFunction::emitSILFunction() + 15860 14 swift-frontend 0x00000001035c2368 swift::irgen::IRGenModule::emitSILFunction(swift::SILFunction*) + 2788 15 swift-frontend 0x00000001033e7c1c swift::irgen::IRGenerator::emitLazyDefinitions() + 5288 16 swift-frontend 0x0000000103573d6c swift::IRGenRequest::evaluate(swift::Evaluator&amp;, swift::IRGenDescriptor) const + 4528 17 swift-frontend 0x00000001035c15c4 swift::SimpleRequest&lt;swift::IRGenRequest, swift::GeneratedModule (swift::IRGenDescriptor), (swift::RequestFlags)17&gt;::evaluateRequest(swift::IRGenRequest const&amp;, swift::Evaluator&amp;) + 180 18 swift-frontend 0x000000010357d1b0 swift::IRGenRequest::OutputType swift::Evaluator::getResultUncached&lt;swift::IRGenRequest, swift::IRGenRequest::OutputType swift::evaluateOrFatalswift::IRGenRequest(swift::Evaluator&amp;, swift::IRGenRequest)::'lambda'()&gt;(swift::IRGenRequest const&amp;, swift::IRGenRequest::OutputType swift::evaluateOrFatalswift::IRGenRequest(swift::Evaluator&amp;, swift::IRGenRequest)::'lambda'()) + 812 19 swift-frontend 0x0000000103576910 swift::performIRGeneration(swift::FileUnit*, swift::IRGenOptions const&amp;, swift::TBDGenOptions const&amp;, std::__1::unique_ptr&lt;swift::SILModule, std::__1::default_deleteswift::SILModule&gt;, llvm::StringRef, swift::PrimarySpecificPaths const&amp;, llvm::StringRef, llvm::GlobalVariable**) + 176 20 swift-frontend 0x0000000102f61af0 generateIR(swift::IRGenOptions const&amp;, swift::TBDGenOptions const&amp;, std::__1::unique_ptr&lt;swift::SILModule, std::__1::default_deleteswift::SILModule&gt;, swift::PrimarySpecificPaths const&amp;, llvm::StringRef, llvm::PointerUnion&lt;swift::ModuleDecl*, swift::SourceFile*&gt;, llvm::GlobalVariable*&amp;, llvm::ArrayRef&lt;std::__1::basic_string&lt;char, std::__1::char_traits, std::__1::allocator&gt;&gt;) + 156 21 swift-frontend 0x0000000102f5d07c performCompileStepsPostSILGen(swift::CompilerInstance&amp;, std::__1::unique_ptr&lt;swift::SILModule, std::__1::default_deleteswift::SILModule&gt;, llvm::PointerUnion&lt;swift::ModuleDecl*, swift::SourceFile*&gt;, swift::PrimarySpecificPaths const&amp;, int&amp;, swift::FrontendObserver*) + 2108 22 swift-frontend 0x0000000102f5c0a8 swift::performCompileStepsPostSema(swift::CompilerInstance&amp;, int&amp;, swift::FrontendObserver*) + 1036 23 swift-frontend 0x0000000102f5f654 performCompile(swift::CompilerInstance&amp;, int&amp;, swift::FrontendObserver*) + 1764 24 swift-frontend 0x0000000102f5dfd8 swift::performFrontend(llvm::ArrayRef&lt;char const*&gt;, char const*, void*, swift::FrontendObserver*) + 3716 25 swift-frontend 0x0000000102ee20bc swift::mainEntry(int, char const**) + 5428 26 dyld 0x0000000188a86b98 start + 6076 Using Xcode 16.4 / Mac OS 16.4
3
0
174
3w
jmp_buf layout for Apple Silicon
Greetings! I am actively working on porting x64 code to Apple Silicon now that the time is nigh and part of the fundamentals of our software is a coroutine library for handling cooperative multitasking of GUI operations on the main thread. I was hoping to get the locations of the stack pointer and frame pointer in jmp_buf so, after setjmp() can redirect them to the primary handling routines in our coroutine library that handles the cooperative scheduling (which replaced and ported the old classic MP routines) which worked for PowerPC, i386 and x64. Any thoughts on where in the jmp_buf these might be located? I didn't see anything in the XNU open source. Any advice would be much obliged instead of having to dive in and re-implement these routines in assembly myself!
7
0
332
3w
Structured concurrency + preconcurrency API (SFAuthorizationPluginView)
I'm having trouble dealing with concurrency with the SFAuthorizationPluginView. Does anybody know how this can be solved? https://developer.apple.com/documentation/securityinterface/sfauthorizationpluginview The crux of it is: If I inherit an object as part of an API, and the API is preconcurrency, and thus is nonisolated (but in reality is @MainActor), how do I return a @MainActor GUI element? https://developer.apple.com/documentation/securityinterface/sfauthorizationpluginview/firstresponder() The longer story: I made my view class inherit SFAuthorizationPluginView. The API is preconcurrency (but not marked as preconcurrency) I started using concurrency in my plugin to retrieve data over XPC. (https://developer.apple.com/documentation/xpc/xpcsession + https://developer.apple.com/documentation/swift/withcheckedthrowingcontinuation(isolation:function:_:)) Once I retrieve the data over XPC, I need to post it on GUI, hence I've set my view class as @MainActor in order to do the thread switch. Swift compiler keeps complaining: override func firstResponder() -&gt; NSResponder? { return usernameField } "Main actor-isolated property 'usernameField' can not be referenced from a nonisolated context; this is an error in the Swift 6 language mode" override func firstResponder() -&gt; NSResponder? { MainActor.assumeIsolated { return usernameField } } "Sending 'self' risks causing data races; this is an error in the Swift 6 language mode" I think fundamentally, the API is forcing me to give away a @MainActor variable through a nonisolated function, and there is no way to shut up the compiler. I've tried @preconcurrency and it has no effect as far as I can tell. I've also tried marking the function explicitly as nonisolated. The rest of the API are less problematic, but returning a GUI variable is exceptionally difficult.
2
0
608
4w
Module compiled with Swift 6.0.3 cannot be imported by the Swift 6.1 compiler
Module compiled with Swift 6.0.3 cannot be imported by the Swift 6.1 compiler: /private/var/tmp/_bazel_xx/8b7c61ad484d9da1bf94a11f12ae6ffd/rules_xcodeproj.noindex/build_output_base/execroot/main/CustomModules/BIYThred/CocoaLumberjack/framework/CocoaLumberjack.framework/Modules/CocoaLumberjack.swiftmodule/arm64-apple-ios.swiftmodule
1
0
661
Jul ’25
Error about "swift for windows" at windows11
谁能告诉我为什么? “[正在运行] swift ”d:\vscode object\swift object\ceshi.swift” JIT 会话错误:未找到符号:[ $ss 27_allocateUninitializedArrayySayxG_BptBwlFyp_Tg5 ] 未能具体化符号: { (main, { main, $sSa 12_endMutationyyF, $ss 5print_9separator10terminatoryypd_S2StFfA0_, $ss 5print_9separator10terminatoryypd_S2StFfA1_, $ss 27_finalizeUninitializedArrayySayxGABnlF }) } [完成] 在 0.47 秒内退出并带有 code=4294967295” 当“Swift for Windows”在 VSCode for Windows 上运行时。 路径为 true,“Package-swift-lsp: Path”为 true。 谁能告诉我为什么?
1
0
797
Jul ’25
AsyncStream does not cancel inner Task
AsyncStream { continuation in Task { let response = await getResponse() continuation.yield(response) continuation.finish() } } In this WWDC video https://developer.apple.com/videos/play/wwdc2025/231/ at 8:20 the presenter mentions that if the "Task gets cancelled, the Task inside the function will automatically get cancelled too". The documentation does not mention anything like this. From my own testing on iOS 18.5, this is not true.
2
0
578
Jul ’25
Passing string between Swift and C++
I want to understand what the recommended way is for string interoperability between swift and c++. Below are the 3 ways to achieve it. Approach 2 is not allowed at work due to restrictions with using std libraries. Approach 1: In C++: char arr[] = "C++ String"; void * cppstring = arr; std::cout<<"before:"<<(char*)cppstring<<std::endl;           // C++ String // calling swift function and passing the void buffer to it, so that swift can update the buffer content Module1::SwiftClass:: ReceiveString (cppstring, length);   std::cout<<"after:"<<(char*)cppstring<<std::endl;             // SwiftStr      In Swift: func ReceiveString (pBuffer : UnsafeMutableRawPointer , pSize : UInt ) -> Void { // to convert cpp-str to swift-str: let swiftStr = String (cString: pBuffer.assumingMemoryBound(to: Int8.self)); print("pBuffer content: \(bufferAsString)"); // to modify cpp-str without converting: let swiftstr:String = "SwiftStr"      _ =  swiftstr.withCString { (cString: UnsafePointer<Int8>) in pBuffer.initializeMemory(as: Int8.self, from: cString, count: swiftstr.count+1) } }  Approach 2:  The ‘String’ type returned from a swift function is received as ‘swift::String’ type in cpp. This is implicitly casted to std::string type. The std::string has the method available to convert it to char *. void TWCppClass::StringConversion () {     // GetSwiftString() is a swift call that returns swift::String which can be received in std::string type     std::string stdstr = Module1::SwiftClass::GetSwiftString ();     char * cstr = stdstr.data ();     const char * conststr= stdstr.c_str (); }    Approach 3: The swift::String type that is obtained from a swift function can be received in char * by directly casting the address of the swift::String. We cannot directly receive a swift::String into a char *. void TWCppClass::StringConversion () {    // GetSwiftString() is a swift call that returns swift::String    swift::String swiftstr = Module1::SwiftClass::GetSwiftString ();    // obtaining the address of swift string and casting it into char *    char * cstr = (char*)&swiftstr; }
3
0
355
Jul ’25
Load bundle resources in UI Tests
I want to load images from my bundle, which works fine when running the main app. However this does not work when running UI Tests. I read that the test bundle is not the main bundle when running tests. I try loading the bundle via this snippet: let bundle = Bundle(for: Frames_HoerspielUITests.self) This is my test class wrapped these the canImport statements so it can be added to the main app target and used for getting the correct bundle: #if canImport(XCTest) import XCTest final class Frames_HoerspielUITests: XCTestCase { override func setUpWithError() throws { continueAfterFailure = false } override func tearDownWithError() throws { } @MainActor func testExample() throws { let app = XCUIApplication() app.launch() } @MainActor func testLaunchPerformance() throws { measure(metrics: [XCTApplicationLaunchMetric()]) { XCUIApplication().launch() } } } #else final class Frames_HoerspielUITests { } #endif However while this works when running the main app, it still fails in the UI tests. It is a SwiftUI only app. and I can't add the images to the asset catalog because they are referenced from another location. Any ideas? Thank you
1
0
248
Jul ’25