Issue:
During app execution, the intended method is not being called; instead, the method preceding (written above the intended method) is being executed.
For Example:
//In my case the ViewController class is at 3rd level of inheritance.
class ViewController: UIViewController {
func methodA() {
print("methodA")
}
func methodB() {
print("methodB")
}
}
let vc = ViewController()
vc.methodB()
Output: //"methodA"
Expected: //"methodB"
Observations:
Recent code changes have revealed that enabling the below Swift-6 flag leads to this linking issue. When this flag is commented out, the problem disappears.
.enableUpcomingFeature("InternalImportsByDefault")
Additionally, moving the intended method into an extension of the same class resolves the issue when the flag is enabled.
Conclusion:
To resolve the issue:
Comment out the Swift-6 flag.
Alternatively, move the method into an extension of the same class, which addresses the issue for this specific case.
I had similar issue in other class where it crashes with message "method not found", but actually the method is there. When moving the method into an extension of same class resolve this issue.
Any help is much appreciated.
Thanking you..
Dive into the world of programming languages used for app development.
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
I ran into a problem, I have a recursive function in which Data type objects are temporarily created, because of this, the memory expands until the entire recursion ends. It would just be fixed using autoreleasepool, but it can't be used with async await, and I really don't want to rewrite the code for callbacks. Is there any option to use autoreleasepool with async await functions? (I Googled one option, that the Task already contains its own autoreleasepool, and if you do something like that, it should work, but it doesn't, the memory is still growing)
func autoreleasepool<Result>(_ perform: @escaping () async throws -> Result) async throws -> Result {
try await Task {
try await perform()
}.value
}
After swapping the -objectAtIndex: method using method_exchangeImplementations, it will cause continuous memory growth.
Connect the iPhone and run the provided project.
Continuously tap the iPhone screen.
Observe Memory; it will keep growing.
Sample code
Topic:
Programming Languages
SubTopic:
General
Tags:
Objective-C Runtime
Xcode Sanitizers and Runtime Issues
Foundation
hi,
Is it possible to compare two vectors and get a boolean answer?
example :
uint642_t a;
uint642_t b;
.../...
if(a == b)
.../...
how to do it ?
thank
I tried to build the project with Xcode 16.3 and I initially got an error that TARGET_IPHONE_SIMULATOR does not exist, then I changed this flag to TARGET_OS_SIMULATOR, but it did not solve the problem
Hi, I'm trying to add Swift code to my Obj-C project. I've gone through all the tutorials and troubleshooting advice I can find online, no dice. I would appreciate any help, thank you so much in advance.
I add a new swift file to my Obj-C project
XCode offers to create a bridging header file for me, yes please
New .swift file and .h file are added to my project no problem
Header file shows up in build settings no problem
I add a new class to my new swift file ("@objc class HelloPrinter: NSObject")
When I build the app, nothing is generated in the bridging header file and the class is obviously inaccessible to my obj-c code
Is this supposed to work? My understanding is that it's supposed to work.
Somewhat concerning is the text that XCode puts in the bridging header file when it's created: "Use this file to import your target's public headers that you would like to expose to Swift."
I don't want to use this bridging header file for anything. I want XCode to GENERATE STUFF in the bridging file. I also don't want to expose anything to Swift. I want the opposite to happen. So I don't get this text at all. Thanks in advance again.
Topic:
Programming Languages
SubTopic:
Swift
I was trying to evaulate
let myTuple = ("blue", false)
let otherTuple = ("blue", true)
if myTuple < otherTuple {
print("yes it evaluates")
}
Ans I got
/tmp/S9jAk7P7KW/main.swift:5:12: error: binary operator '<' cannot be applied to two '(String, Bool)' operands
if myTuple < otherTuple {
My question is why there is no compile time issue in first place where the declaration is
let myTuple = ("blue", false)
~~~~~~
something like above
Given the below code with Swift 6 language mode, Xcode 16.2
If running with iOS 18+: the app crashes due to _dispatch_assert_queue_fail
If running with iOS 17 and below: there is a warning: warning: data race detected: @MainActor function at Swift6Playground/PublishedValuesView.swift:12 was not called on the main thread
Could anyone please help explain what's wrong here?
import SwiftUI
import Combine
@MainActor
class PublishedValuesViewModel: ObservableObject {
@Published var count = 0
@Published var content: String = "NA"
private var cancellables: Set<AnyCancellable> = []
func start() async {
let publisher = $count
.map { String(describing: $0) }
.removeDuplicates()
for await value in publisher.values {
content = value
}
}
}
struct PublishedValuesView: View {
@ObservedObject var viewModel: PublishedValuesViewModel
var body: some View {
Text("Published Values: \(viewModel.content)")
.task {
await viewModel.start()
}
}
}
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!
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<T> {
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..<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)?
I have been recently getting the following error seemingly randomly, when an event handler of a SwiftUI view accesses a relationship of a SwiftData model the view holds a reference to. I haven't yet found a reliable way of reproducing it:
SwiftData/BackingData.swift:866: Fatal error: This model instance was invalidated
because its backing data could no longer be found the store.
PersistentIdentifier(id: SwiftData.PersistentIdentifier.ID(url: COREDATA_ID_URL),
implementation: SwiftData.PersistentIdentifierImplementation)
What could cause this error? Could you suggest me a workaround?
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
i am trying to build my code and have ran into this error.
"Trailing closure passed to parameter of type 'DispatchWorkItem' that does not accept a closure"
i have been trying to figure it out for so long, and even ai cant figure it out. is this a bug, or am i missing some obvious way to fix this ?
func loadUser(uid: String, completion: (() -> Void)? = nil) {
db.collection("users").document(uid).getDocument { [weak self] snapshot, error in
guard let data = snapshot?.data(), error == nil else { completion?(); return }
DispatchQueue.main.async {
self?.currentUser = User(
username: data["username"] as? String ?? "Learner",
email: data["email"] as? String ?? "",
profileImageName: "person.circle.fill",
totalXP: data["totalXP"] as? Int ?? 0,
currentStreak: data["currentStreak"] as? Int ?? 0,
longestStreak: data["longestStreak"] as? Int ?? 0,
level: data["level"] as? Int ?? 1,
levelProgress: data["levelProgress"] as? Double ?? 0.0,
xpToNextLevel: data["xpToNextLevel"] as? Int ?? 100,
completedLessons: data["completedLessons"] as? [String] ?? []
)
self?.saveUser()
completion?()
}
}
}
I get this red warning in Xcode every time my app is syncing to the iCloud. My model has only basic types and enum that conform to Codable so i'm not sure what is the problem.
App is working well, synchronization works. But the warning doesn't look good.
Maybe someone has idea how to debug it.
According to the doc:
The value returned is the same as the value returned in the kEventParamKeyCode when using Carbon Events.
So where can I find kEventParamKeyCode?
Hi all,
In Swift, I often see static helper functions grouped in an enum without any cases, like this:
enum StringUtils {
static func camelCaseToSnakeCase(_ input: String) -> String {
// implementation
}
}
Since this enum has no cases, it cannot be instantiated – which is exactly the point.
It’s meant to group related functionality without any stored state, and without the need for instantiation.
This pattern avoids writing a struct with a private init() and makes the intent clearer:
"This is just a static utility, not an object."
You’ll often see this used for things like:
AnalyticsEvents.track(_:)
My question:
Is this use of a case-less enum considered good practice in Swift when building static-only helpers?
Or is there a better alternative for expressing intent and preventing instantiation?
I’d appreciate any insight – especially if there’s official guidance or references from the Swift core team.
Thanks!
Topic:
Programming Languages
SubTopic:
Swift
What is the most obvious method of calling StoreKit from C++. I'm getting blocked by the fact that most of the critical StoreKit calls are async and functions marked a sync don't show up in the swift header for me to call from C++ (at least as far as I can tell).
I'm trying to call
let result = try await Product.products(for:productIDs) or
let result = try await product.purchase()
And C++ can't even see any functions I wrap these in as far as I can tell because i have to make them async. What am I missing?
I tried a lot of alternates, like wrapping in
Task { let result = try await Product.products(for:productIDs) }
and it gives me 'Passing closure as a sending parameter' errors.
Also when I try to call the same above code it gives me 'initializtion of immutable value never used' errors and the variables never appear.
Code:
struct storeChooser {
public var productIDs: [String]
public function checkProduct1 {
Task { let result = try await Product.products(for: productIDs) }
The above gives the initialization of immutable value skipped, and when I create a
@State var products
Then I get the 'passing closure as a sending parameter' error when i try to run it in a task
it appears if I could make the function async and call it from C++ and have it return nothing it may work, does anyone know how to get C++ to see an async function in the -Swift.h file?
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.
Hello,
While watching WWDC25: Code-along: Elevate an app with Swift concurrency at timestamp 25:48, I noticed something in the slide/diagram that might be incorrect.
The diagram shows ExtractSticker twice, but based on the code context and spoken explanation, I think it was meant to be ExtractSticker and ExtractColor.
Reasoning:
The surrounding code and narration describe the use of async let and a Sendable Data object.
From the flow, one task extracts a sticker while the other extracts a color, so it seems like the diagram is inconsistent.
I do understand that with @concurrent, having two ExtractSticker operations on the same Data is technically possible (with two concurrent process executing their respective ExtractSticker) — but that would be a different meaning than what the talk was describing.
Since concurrency is already a subtle and error-prone topic, I thought it was worth pointing this out. If I’m mistaken, I’d love clarification. Otherwise, this could be a small correction to keep things aligned and clearer for everyone.
Minor point overall, but Swift 6’s concurrency model is doing a fantastic job at helping us write safer code—so thank you to the team for that!
(Attaching screenshots for reference)
I’m creating an app using SwiftUI, and I would like to incorporate a small Java codebase that I created for the Android version of the app. Is there a way to package the Java code to work on iOS and macOS
Topic:
Programming Languages
SubTopic:
General