I am using swiftui lately in my iOS mobile app, The Mobile app already has a pipeline that detect any experimental features and throw an error
I am using swift 5 and as you all know SwiftUI is using some of OpaqueTypeErasure utility types like "some"
I heard that in swift 6 the OpaqueTypeErasure is not experimental anymore
But upgrading the app swift version will be a very long process
Also changing the pipeline will be a very long and tiring process
So i want to know if there is a way to remove OpaqueTypeErasure from SwiftUI and what is the alternatives for bypassing the error that being thrown from the pipeline
Dive into the world of programming languages used for app development.
Post
Replies
Boosts
Views
Activity
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) > 0
#define USING_BLE_SERVICE
...
#if 0 BLE_SERVICE_LIST(BLE_SERVICE_BLANK, BLE_CHARACTERISTIC_ENUM_COUNTER) > 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.
I used struct in the swift file, but once I use xcode build. It will automatically change to enum, causing build failure. But it turns out that this file can be used to build. Since upgrading to XCode16.1, it's not working anymore. I don't know where to set it up. Do not optimize or modify my code.
Error message: 'Padding' cannot be constructed because it has no accessible initializers
My environment is:
macos sequoia 15.1
xcode 16.1(16B40)
File source code:
let π: CGFloat = .pi
let customUserAgent: String = "litewallet-ios"
let swiftUICellPadding = 12.0
let bigButtonCornerRadius = 15.0
enum FoundationSupport {
static let dashboard = "https://support.litewallet.io/"
}
enum APIServer {
static let baseUrl = "https://api-prod.lite-wallet.org/"
}
enum Padding {
subscript(multiplier: Int) -> CGFloat {
return CGFloat(multiplier) * 8.0
}
subscript(multiplier: Double) -> CGFloat {
return CGFloat(multiplier) * 8.0
}
}
enum C {
static let padding = Padding()
enum Sizes {
static let buttonHeight: CGFloat = 48.0
static let sendButtonHeight: CGFloat = 165.0
static let headerHeight: CGFloat = 48.0
static let largeHeaderHeight: CGFloat = 220.0
}
static var defaultTintColor: UIColor = UIView().tintColor
Enum was originally SRTUCT. But the build has been automatically optimized
I would like to see examples of how to do this. Apple states that explicit clang modules don't work with C++ interop. ObjC++ has simple interop with C++. Swift does not. And so I'd like to know how to setup my C++ projects to build them as clang modules.
I have an app whose logic is in C++ and rest of the parts (UI) are in Swift and SwiftUI.
Exceptions can occur in C++ and Swift. I've got the C++ part covered by using the Linux's signal handler mechanism to trap signals which get raised due to exceptions.
But how should I capture exceptions in Swift? When I say exceptions in Swift, I mean, divide by zero, force unwrapping of an optional containing nil, out of index access in an array, etc. Basically, anything that can go wrong, I don't want my app to abruptly crash... I need a chance to finalise my stuff, alert the user, prepare diagnostic reports and terminate. I'm looking for a 'catch-all' exception handler. As an example, let's take Android. In Android, there is the setDefaultUncaughtExceptionHandler method to register for all kinds of exceptions in any thread in Kotlin. I'm looking for something similar in Swift that should work for macOS, iOS & iPadOS, tvOS and watchOS.
I first came across the NSSetUncaughtExceptionHandler method. My understanding is, this only works when I explicitly raise NSExceptions. When I tested it, observed that the exception handler didn't get invoked for either case - divide by zero or invoking raise.
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
Log("AppDelegate.applicationDidFinishLaunching(_:)")
// Set the 'catch-all' exception handler for Swift exceptions.
Log("Registering exception handler using NSSetUncaughtExceptionHandler()...")
NSSetUncaughtExceptionHandler { (exception: NSException) in
Log("AppDelegate.NSUncaughtExceptionHandler()")
Log("Exception: \(exception)")
}
Log("Registering exception handler using NSSetUncaughtExceptionHandler() succeeded!")
// For C++, use the Linux's signal mechanism.
ExceptionHandlingCpp.RegisterSignals()
//ExceptionHandlingCpp.TestExceptionHandler()
AppDelegate.TestExceptionHandlerSwift()
}
static func TestExceptionHandlerSwift() {
Log("AppDelegate.TestExceptionHandlerSwift()")
DivisionByZero(0)
}
private static func DivisionByZero(_ divisor: Int) {
Log("AppDelegate.DivisionByZero()")
let num1: Int = 2
Log("Raising Exception...")
//let result: Int = num1/divisor
let exception: NSException = NSException(name: NSExceptionName(rawValue: "arbitrary"), reason: "arbitrary reason", userInfo: nil)
exception.raise()
Log("Returning from DivisionByZero()")
}
}
In the above code, dividing by zero, nor raising a NSException invokes the closure passed to NSSetUncaughtExceptionHandler, evident from the following output logs
AppDelegate.applicationWillFinishLaunching(_:)
AppDelegate.applicationDidFinishLaunching(_:)
Registering exception handler using NSSetUncaughtExceptionHandler()...
Registering exception handler using NSSetUncaughtExceptionHandler() succeeded!
ExceptionHandlingCpp::RegisterSignals()
....
AppDelegate.TestExceptionHandlerSwift()
AppDelegate.DivisionByZero()
Raising Exception...
Currently, I'm reading about ExceptionHandling framework, but this is valid only for macOS.
What is the recommended way to capture runtime issues in Swift?
We are seeing a crash on Big Sur 11.7.10 after switching the build system to use Xcode 15
Excerpt from crash
Time Awake Since Boot: 1700 seconds
System Integrity Protection: enabled
Crashed Thread: 0
Exception Type: EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Exception Note: EXC_CORPSE_NOTIFY
Termination Reason: DYLD, [0x4] Symbol missing
Application Specific Information:
dyld: launch, loading dependent libraries
Dyld Error Message:
Symbol not found: __ZNSt3__17codecvtIDiDu11__mbstate_tE2idE
Referenced from: /Applications/SecureworksTaegis.app/Contents/MacOS/com.secureworks.agent.daemon.app/Contents/MacOS/com.secureworks.agent.daemon
Expected in: /usr/lib/libc++.1.dylib
in /Applications/SecureworksTaegis.app/Contents/MacOS/com.secureworks.agent.daemon.app/Contents/MacOS/com.secureworks.agent.daemon
Build system has the following specs :
ProductName: macOS
ProductVersion: 14.3.1
BuildVersion: 23D60
Xcode 15.2
Build version 15C500b
CMAKE PROPS
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_OSX_DEPLOYMENT_TARGET 11.0)
I wonder if this is correct behavior. I was surprised to get this result when compiling and running the following C code with Apple clang version 14.0.0 (clang-1400.0.29.102) target arm64-apple-darwin21.6.0 on a M1 Pro 12.7.6 with cc -O2 file.c:
#include <stdio.h>
#include <stdlib.h>
unsigned long long factorial(int n)
{
unsigned long long fac = 1;
while (n > 0)
fac *= n;
return fac;
}
int main()
{
return factorial(1);
}
Compiling with -O2 and running this code gives "Trace/BPT trap".
Checking with LLDB:
$ lldb ./a.out
(lldb) target create "./a.out"
Current executable set to '/Users/engelen/Projects/Euler/a.out' (arm64).
(lldb) run
Process 79580 launched: '/Users/engelen/Projects/Euler/a.out' (arm64)
Process 79580 stopped
* thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BREAKPOINT (code=1, subcode=0x100003fb4)
frame #0: 0x0000000100003fb4 a.out`main at 20.c:9:3 [opt]
6 unsigned long long fac = 1;
7 while (n > 0)
8 fac *= n;
-> 9 return fac;
10 }
11
12 int main()
The loop is non-terminating. But a breakpoint trap is triggered at the return statement. The code should just hang in the loop IMO, not trap, because it never updates variable n (a correct factorial function should decrement n). Never seen this before (not since I started wiring C code in the 80s.)
If I change the update *= into += then there is no trap.
hi
i want create a commande line tool for arm64 et intel x86-64
Xcode 16 macbook pro M3
my setting :
and
but my application compile only for arm64
who can explain to me ?
This is similar to this post https://developer.apple.com/forums/thread/700770 on using objc_copyClassList to obtain the available classes. When iterating the list, I try casting the result to an instance of a protocol and that works fine:
protocol DynamicCounter {
init(controlledByPlayer: Bool, game: Game)
}
class BaseCounter: NSObject, DynamicCounter {
}
static func withAllClasses<R>(
_ body: (UnsafeBufferPointer<AnyClass>) throws -> R
) rethrows -> R {
var count: UInt32 = 0
let classListPtr = objc_copyClassList(&count)
defer {
free(UnsafeMutableRawPointer(classListPtr))
}
let classListBuffer = UnsafeBufferPointer(
start: classListPtr, count: Int(count)
)
return try body(classListBuffer)
}
static func initialize() {
let monoClasses = withAllClasses { $0.compactMap { $0 as? DynamicCounter.Type } }
for cl in monoClasses {
cl.initialize()
}
}
The above code works fine if I use DynamicCounter.Type on the cast but crashes if try casting to BaseCounter.Type instead.
Is there a way to avoid the weird and non Swift classes?
I have a problem with the following code, I am not being notified of changes to the progress property of my Job object, which is @Observable... This is a command-line Mac application (the same code works fine in a SwiftUI application).
I must have missed something?
do {
let job = AsyncJob()
withObservationTracking {
let progress = job.progress
} onChange: {
print("Current progress: \(job.progress)")
}
let _ = try await job.run()
print("Done...")
} catch {
print(error)
}
I Try this without any success:
@main
struct MyApp {
static func main() async throws {
// my code here
}
}
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
Hi,
Considering this method I'd like to test:
public func play(_ soundFileName: String, shouldLoop: Bool) {
Task {
await dataSource.play(soundFileName, shouldLoop: shouldLoop)
}
}
Previously, with XCTest we could use an expectation and wait for it to be fulfilled:
func test()
sut.play("", shouldLoop: false)
wait(for: [mockedAudioPlayerDataSource.invokedPlayExpectation])
XCTAssertEqual(mockedAudioPlayerDataSource.invokedPlayCount, 1)
With Swift Testing, I am unsure what a unit test looks like.
i have macos 15 and xcode 16 swift 6 and want to make apps
to run on macintosh.
i know the syntax of this programming language, but i need
informations like which libraries i have to import for func's
which name i do not know, and parameters i have not found
on websites or the tutorial on swift.
i need procedures like
open window at x,y,width,height
draw rectangle at x,y,width,height,color
draw text at x,y,width,height,color,size
read keyboard-letter,up/dn,shift
read mouse x,y,buttons
I want to be able to write a cross-platform screensaver that works on both Windows and macOS using the Pygame 2D graphics library in Python. On Windows, this is super easy - you just write your program with three possible command line arguments: /p for preview mode, /c for the configuration dialog mode, and /s for the actual full-screen screensaver mode. Then you just use pyinstaller to build an .exe file and rename the extension to .scr, and you're good to go. However, it seems that making a screensaver on macOS is a pretty convoluted process, and there was stuff about specific Objective-C functions that you had to write, and I didn't really understand the documentation. Could you please tell me if there is any way to simply get my Python Pygame program to build as a proper .saver file? Thanks!
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?
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
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
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!
Hi, I have issue on build my react native project and got this error "Undefined symbol: _swift_willThrowTypedImpl" how can I fix it?
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))")
}
}
}