This topic area is about the programming languages themselves, not about any specific API or tool. If you have an API question, go to the top level and look for a subtopic for that API. If you have a question about Apple developer tools, start in the Developer Tools & Services topic.
For Swift questions:
If your question is about the SwiftUI framework, start in UI Frameworks > SwiftUI.
If your question is specific to the Swift Playground app, ask over in Developer Tools & Services > Swift Playground
If you’re interested in the Swift open source effort — that includes the evolution of the language, the open source tools and libraries, and Swift on non-Apple platforms — check out Swift Forums
If your question is about the Swift language, that’s on topic for Programming Languages > Swift, but you might have more luck asking it in Swift Forums > Using Swift.
General:
Forums topic: Programming Languages
Swift:
Forums subtopic: Programming Languages > Swift
Forums tags: Swift
Developer > Swift website
Swift Programming Language website
The Swift Programming Language documentation
Swift Forums website, and specifically Swift Forums > Using Swift
Swift Package Index website
Concurrency Resources, which covers Swift concurrency
How to think properly about binding memory Swift Forums thread
Other:
Forums subtopic: Programming Languages > Generic
Forums tags: Objective-C
Programming with Objective-C archived documentation
Objective-C Runtime documentation
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
Dive into the world of programming languages used for app development.
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Created
Hello everyone! I am trying to wrap a ViewModifier inside a Swift Package that bundles a metal shader file to be used in the modifier. Everything works as expected in the Preview, in the Simulator and on a real device for iOS. It also works in Preview and in the Simulator for tvOS but not on a real AppleTV. I have tried this on a 4th generation Apple TV running tvOS 26.3 using Xcode 26.2.0.
Xcode logs the following: The metallib is processed and exists in the bundle.
Compiler failed to build request
precondition failure: pipeline error: custom_effect-fg2a5cia7fmha4: error: unresolved visible function reference: custom_fn
Reason: visible function not loaded
Compiler failed to build request
precondition failure: pipeline error: custom_effect-fg2a5cia7fmha4: error: unresolved visible function reference: custom_fn
Reason: visible function not loaded
Compiler failed to build request
precondition failure: pipeline error: custom_effect-fg2a5cia7fmha4: error: unresolved visible function reference: custom_fn
Reason: visible function not loaded
Compiler failed to build request
precondition failure: pipeline error: custom_effect-fg2a5cia7fmha4: error: unresolved visible function reference: custom_fn
Reason: visible function not loaded
Compiler failed to build request
precondition failure: pipeline error: custom_effect-fg2a5cia7fmha4: error: unresolved visible function reference: custom_fn
Reason: visible function not loaded
Compiler failed to build request
precondition failure: pipeline error: custom_effect-fg2a5cia7fmha4: error: unresolved visible function reference: custom_fn
Reason: visible function not loaded
Contents of Package.swift:
import PackageDescription
let package = Package(
name: "Test",
platforms: [
.iOS(.v17),
.tvOS(.v17)
],
products: [
.library(
name: "Test",
targets: [
"Test"
]
)
],
targets: [
.target(
name: "Test",
resources: [
.process("Shaders")
]
),
.testTarget(
name: "TestTests",
dependencies: [
"Test"
]
)
]
)
Content of my metal file:
#include <metal_stdlib>
using namespace metal;
[[ stitchable ]] float2 complexWave(float2 position, float time, float2 size, float speed, float strength, float frequency) {
float2 normalizedPosition = position / size;
float moveAmount = time * speed;
position.x += sin((normalizedPosition.x + moveAmount) * frequency) * strength;
position.y += cos((normalizedPosition.y + moveAmount) * frequency) * strength;
return position;
}
And my ViewModifier:
import MetalKit
import SwiftUI
extension ShaderFunction {
static let complexWave: ShaderFunction = {
ShaderFunction(
library: .bundle(.module),
name: "complexWave"
)
}()
}
extension Shader {
static func complexWave(arguments: [Shader.Argument]) -> Shader {
Shader(function: .complexWave, arguments: arguments)
}
}
struct WaveModifier: ViewModifier {
let start: Date = .now
func body(content: Content) -> some View {
TimelineView(.animation) { context in
let delta = context.date.timeIntervalSince(start)
content
.visualEffect { view, proxy in
view.distortionEffect(
.complexWave(
arguments: [
.float(delta),
.float2(proxy.size),
.float(0.5),
.float(8),
.float(10)
]
),
maxSampleOffset: .zero
)
}
}
.onAppear {
let paths = Bundle.module.paths(forResourcesOfType: "metallib", inDirectory: nil)
print(paths)
}
}
}
extension View {
public func wave() -> some View {
modifier(WaveModifier())
}
}
#Preview {
Image(systemName: "cart")
.wave()
}
Any help is appreciated.
Hi everyone,
I’m facing an issue with CloudKit sync getting stuck during initial device migration in my SwiftData-based app.
The app follows a local-first architecture using SwiftData + CloudKit sync, and works correctly for:
✔ Incremental sync
✔ Bi-directional updates
✔ Small datasets
However, when onboarding a new device with large historical data, sync becomes extremely slow or appears stuck. Even after two hours data is not fully synced. ~6900 Transactions
🚨 Problem
When installing the app on a new iPhone and enabling iCloud sync:
• Initial hydration starts
• A small amount of data syncs
• Then sync stalls indefinitely
Observed behaviour:
• iPhone → Mac sync works (new changes sync back)
• Mac → iPhone large historical migration gets stuck
• Reinstalling app / clearing container does not resolve issue
• Sync never completes full migration
This gives the impression that:
CloudKit is trickling data but not progressing after a certain threshold.
The architecture is:
• SwiftData local store
• Manual CloudKit sync layer
• Local-first persistence
• Background push/pull sync
So I understand:
✔ Conflict resolution is custom
✔ Initial import may not be optimized by default
But I expected CloudKit to eventually deliver all records.
Instead, the new device remains permanently in a “partial state”.
⸻
🔍 Observations
• No fatal CloudKit errors
• No rate-limit errors
• No quota issues
• iCloud is available
• Sync state remains “Ready”
• Hydration remains “mostlyReady”
Meaning:
CloudKit does not report failure — but data transfer halts.
⸻
🤔 Questions
Would appreciate guidance on:
Is CloudKit designed to support large initial dataset migration via manual sync layers?
Or is this a known limitation vs NSPersistentCloudKitContainer?
⸻
Does CloudKit internally throttle historical record fetches?
Could it silently stall without error when record volume is high?
⸻
Is there any recommended strategy for:
• Bulk initial migration
• Progressive hydration
• Forcing forward sync progress
⸻
Should initial migration be handled outside CloudKit (e.g. via file transfer / backup restore) before enabling sync?
⸻
🎯 Goal
I want to support:
• Large historical onboarding
• Multi-device sync
• User-visible progress
Without forcing migration to Core Data.
⸻
🙏 Any advice on:
• Best practices
• Debugging approach
• CloudKit behavior in such scenarios
would be greatly appreciated.
Thank you!
Topic:
Programming Languages
SubTopic:
Swift
Tags:
Swift Packages
CloudKit
Swift
Cloud and Local Storage
In my CarPlaySceneDelegate.swift, I have two tabs:
The first tab uses a CPListImageRowItem with a CPListImageRowItemRowElement. The scroll direction is inverted, and the side button does not function correctly.
The second tab uses multiple CPListItem objects. There are no issues: scrolling works in the correct direction, and the side button behaves as expected.
Steps To Reproduce
Launch the app.
Connect to CarPlay.
In the first tab, scroll up and down, then use the side button to navigate.
In the second tab, scroll up and down, then use the side button to navigate.
As observed, the scrolling behavior is different between the two tabs.
Code Example:
import CarPlay
import UIKit
class CarPlaySceneDelegate: UIResponder, CPTemplateApplicationSceneDelegate {
var interfaceController: CPInterfaceController?
func templateApplicationScene(
_ templateApplicationScene: CPTemplateApplicationScene,
didConnect interfaceController: CPInterfaceController
) {
self.interfaceController = interfaceController
downloadImageAndSetupTemplates()
}
func templateApplicationScene(
_ templateApplicationScene: CPTemplateApplicationScene,
didDisconnectInterfaceController interfaceController: CPInterfaceController
) {
self.interfaceController = nil
}
private func downloadImageAndSetupTemplates() {
let urlString = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRcYUjd1FYkF04-8Vb7PKI1mGoF2quLPHKjvnR7V4ReZR8UjW-0NJ_kC7q13eISZGoTCLHaDPVbOthhH9QNq-YA0uuSUjfAoB3PPs1aXQ&s=10"
guard let url = URL(string: urlString) else {
setupTemplates(with: UIImage(systemName: "photo")!)
return
}
URLSession.shared.dataTask(with: url) { [weak self] data, _, _ in
let image: UIImage
if let data = data, let downloaded = UIImage(data: data) {
image = downloaded
} else {
image = UIImage(systemName: "photo")!
}
DispatchQueue.main.async {
self?.setupTemplates(with: image)
}
}.resume()
}
private func setupTemplates(with image: UIImage) {
// Tab 1 : un seul CPListImageRowItem avec 12 CPListImageRowItemRowElement
let elements: [CPListImageRowItemRowElement] = (1...12).map { index in
CPListImageRowItemRowElement(image: image, title: "test \(index)", subtitle: nil)
}
let rowItem = CPListImageRowItem(text: "Images", elements: elements, allowsMultipleLines: true)
rowItem.listImageRowHandler = { item, elementIndex, completion in
print("tapped element \(elementIndex)")
completion()
}
let tab1Section = CPListSection(items: [rowItem])
let tab1Template = CPListTemplate(title: "CPListImageRowItemRowElement", sections: [tab1Section])
// Tab 2 : 12 CPListItem simples
let tab2Items: [CPListItem] = (1...12).map { index in
let item = CPListItem(text: "Item \(index)", detailText: "Detail \(index)")
item.handler = { _, completion in
print("handler Tab 2")
completion()
}
return item
}
let tab2Section = CPListSection(items: tab2Items)
let tab2Template = CPListTemplate(title: "CPListItem", sections: [tab2Section])
// CPTabBarTemplate avec les deux tabs
let tabBar = CPTabBarTemplate(templates: [tab1Template, tab2Template])
interfaceController?.setRootTemplate(tabBar, animated: true)
}
}
Here is a quick video:
In this code, I use in some places
required init?(coder: (NSCoder?)) {
// Init some properties
super.init(coder: coder!)
}
And in other places
required init?(coder: NSCoder) {
super.init(coder: coder)
// Init some properties
}
Both seem to work. Is there a preferred one ? In which cases ? Or should I always use the second one ?
And can super be called at anytime ?
I currently have a iOS app live on the App Store but I also want to release it on Android, the whole code is in Swift so would that be possible or would I have to rewrite my whole apps code in a different coding language.
I am implementing the FFT using vDSP.DiscreteFourierTransform. According to the official documentation, the count parameter has requirements as outlined below:
/// The `count` parameter must be:
/// * For split-complex real-to-complex: `2ⁿ` or `f * 2ⁿ`, where `f` is `3`, `5`, or `15` and `n >= 4`.
/// * For split-complex complex-to-complex: `2ⁿ` or `f * 2ⁿ`, where `f` is `3`, `5`, or `15` and `n >= 3`.
/// * For interleaved: `f * 2ⁿ`, where `f` is `2`, `3`, `5`, `3x3`, `3x5`, or `5x5`, and `n>=2`.
Despite adhering to these specifications in theory, my attempt to initialize an interleaved DFT with count = 2 * 2 * 5 * 5 (equivalent to 5×5 × 2²) resulted in a failure. Below is the code snippet I used for the initialization:
do {
let dft = try vDSP.DiscreteFourierTransform(
previous: nil,
count: 2 * 2 * 5 * 5,
direction: .forward,
transformType: .complexReal,
ofType: DSPComplex.self
)
print(dft)
} catch {
print("DFT init failed:", error)
}
Could somebody more knowledgeable with these APIs have a look? Thanks!
I think that it would be helpful to have better interoperability between Swift and JavaScript. There are a lot of useful packages on NPM that don't have equivalents for Swift. It would be helpful if Apple provided easier ways to use NPM packages in a Swift project. Currently, the JavaScriptCore framework is missing many standard things used in many packages, like the fetch API. It would be helpful to be able to run sandboxed JavaScript code inside of a Swift app but allow access to specific domains, folders, etc., using a permissions system similar to Deno.
I want to use the Observations AsyncSequence on some SwiftData @Model instances to determine if internal calculations need to be done.
When a simple property is linked to the Observations it fires CONTINUOUSLY even though no change is made to the model property.
Also, when I try to observe a property which is a list of another @Model type the Observations sequence does not fire when I add or remove items.
I am hoping to use the async-algorithm's merge function so all the associated sequences can be combined since if any of the associated events should fire the calculation event.
This is a continuation of https://developer.apple.com/forums/thread/795348
I rambled too much and did not understand the underlaying problem.
The problem is that I have a C function in a iOS library. I want to call this C function from a dylib that this library loads on runtime. When running directly from Xcode (either in debug or release mode) this works correctly. However, when the app is uploaded to testflight or distributed for debugging then the function is stripped and a null function pointer exception crashes the app.
In the last post it was really hard to explain and I was pressed on time but I've created a minimal reproducible example:
https://github.com/ospfranco/dylib_crash
The instructions to run and reproduce the crash are on the README.
Topic:
Programming Languages
SubTopic:
General
Tags:
Swift Packages
Xcode Static Analyzer
Objective-C
Does anyone know if the resources .copy rule in a Swift .package file is supposed to recursively copy the full contents if it's pointed at a directory?
The docs say…
If you pass a directory path to the copy rule, the compiler retains the directory’s structure.
…but you can interpret that in a few different ways.
It also doesn’t appear to work if the directory you specify only contains directories.
When I try to invoke the tkinter module in Python 3 that is bundled with Xcode Developer Tools, I get a message saying that my system version is too low:
$ /usr/bin/python3 -m tkinter
macOS 26 (2602) or later required, have instead 16 (1602) !
zsh: abort /usr/bin/python3 -m tkinter
It seems like the system version reported is macOS 16, which I assume is the version code before the decision to rename all OS platforms to 26. This is a very low level mistake and should be fixed as soon as possible.
Topic:
Programming Languages
SubTopic:
General
In trying to convert some Objective-C to Swift, I have a subclass of NSWindowController and want to write a convenience initializer. The documentation says
You can also implement an NSWindowController subclass to avoid requiring client code to get the corresponding nib’s filename and pass it to init(windowNibName:) or init(windowNibName:owner:) when instantiating the window controller. The best way to do this is to override windowNibName to return the nib’s filename and instantiate the window controller by passing nil to init(window:).
My attempt to do that looks like this:
class EdgeTab: NSWindowController
{
override var windowNibName: NSNib.Name? { "EdgeTab" }
required init?(coder: NSCoder)
{
super.init(coder: coder)
}
convenience init()
{
self.init( window: nil )
}
}
But I'm getting an error message saying "Incorrect argument label in call (have 'window:', expected 'coder:')". Why the heck is the compiler trying to use init(coder:) instead of init(window:)?
So I’m writing a program, as a developer would - ‘with Xcode.’
Code produced an error.
The key values were swapped. The parameters suggested were ‘optional parameters variables.’
“var name: TYPE? = (default)”
var name0: TYPE
=============================
name0 = “super cool”
‘Name is not yet declared at this point
provided with
x - incorrect argument replace
ExampleStruct(name:”supercool”)
should be
x - incorrect argument replace
ExampleStruct(name0:”supercool”)
=============================
In swift, there is a procedural prioritization within the constructor calling process.
Application calls constructor.
Constructor provides constructor signature. Signature requires parameters & throws an error if the params are not in appropriate order. - “got it compiler; thank you, very much”
Typically, when this occurs, defaults will be suggested. Often the variable type. Ie String, Bool.
such as:
StructName(param1:Int64, param2:Bool)
(Recently, I have seen a decline in @Apple’s performance in many vectors.)
As stated before, the key value pairs were out of sequence. The optionals were suggested instead of the required parameters.
This leads me to believe that there is an order of operations in the calling procedure that is being mismanaged.
I.e. regular expression, matching with optional. This confuses these with [forced, required] parameters, and the mismanagement of ‘key: value’ pairs.
this is a superficial prognosis and would like to know if anyone has any insight as to why this may occur.
Could it be a configuration setting? Is it possibly the network I connected to bumped into something. Etc..
I appreciate any and all feedback.
Please take into consideration the Apple developer forum, guidelines before posting comments.
#dev_div
Hi There,
I have been using my Mac Studio to complete some work in Python (which I normally do in Linux) and recently I got this error which has completely stopped all development as venvs will no longer work correctly:
WARNING: Ignoring invalid distribution ... (and then whichever apps are currently installed in the venv
This occurs for me on every install of any version of Python installed using any of the standard methods (installer). I've tried all the main points of advice on knowledgeable forums, but the difference between Python on Sequoia and Python on Linux is enough such that I am at an end of my debugging knowledge. I've even attempted to blast away any System Python changes with a recovery reinstall, but the problem persists. I've done almost exactly the same setup on my MacBook Air and it is fine ... but the Studio is now unavailable for Python development.
I know I have probably dropped the ball somewhere but can't see the error myself so, I'm wondering if I should just blast away everything on the machine and go through the process of doing a clean install. Asking the experts in MacOS here so I can avoid the pain of doing that!
Topic:
Programming Languages
SubTopic:
General
macOS Tahoe ships with Ruby 2.6.10 which was End Of Life in April 2022 (https://www.ruby-lang.org/en/downloads/branches/). How can I either upgrade it to Ruby 3.4.7 or delete it, so that my mac meets minimum cybersecurity requirements?
I use rbenv for more recent versions of Ruby at the moment so don't need any suggestions on how to do add them, I just need rid of the dangerously out of date system Ruby, thanks.
Topic:
Programming Languages
SubTopic:
General
Title
Why doesn’t this async function see external changes to an inout Bool in Release builds (but works in Debug)?
Body
I have a small helper function that waits for a Bool flag to become true with a timeout:
public func test(binding value: inout Bool, timeout maximum: Int) async throws {
var count = 0
while value == false {
count += 1
try await Task.sleep(nanoseconds: 0_100_000_000)
if value == true {
return
}
if count > (maximum * 10) {
return
}
}
}
I call like this:
var isVPNConnected = false
adapter.start(tunnelConfiguration: tunnelConfiguration) { [weak self] adapterError in
guard let self = self else { return }
if let adapterError = adapterError {
} else {
isVPNConnected = true
}
completionHandler(adapterError)
}
try await waitUntilTrue(binding: &isVPNConnected, timeout: 10)
What I expect:
test should keep looping until flag becomes true (or the timeout is hit).
When the second task sets flag = true, the first task should see that change and return.
What actually happens:
In Debug builds this behaves as expected: when the second task sets flag = true, the loop inside test eventually exits.
In Release builds the function often never sees the change and gets stuck until the timeout (or forever, depending on the code). It looks like the while value == false condition is using some cached value and never observes the external write.
So my questions are:
Is the compiler allowed to assume that value (the inout Bool) does not change inside the loop, even though there are await suspension points and another task is mutating the same variable?
Is this behavior officially “undefined” because I’m sharing a plain Bool across tasks without any synchronization (actors / locks / atomics), so the debug build just happens to work?
What is the correct / idiomatic way in Swift concurrency to implement this kind of “wait until flag becomes true with timeout” pattern?
Should I avoid inout here completely and use some other primitive (e.g. AsyncStream, CheckedContinuation, Actor, ManagedAtomic, etc.)?
Is there any way to force the compiler to re-read the Bool from memory each iteration, or is that the wrong way to think about it?
Environment (if it matters):
Swift: [fill in your Swift version]
Xcode: [fill in your Xcode version]
Target: iOS / macOS [fill in as needed]
Optimization: default Debug vs. Release settings
I’d like to understand why Debug vs Release behaves differently here, and what the recommended design is for this kind of async waiting logic in Swift.
After switching our iOS app project from Swift 5 to Swift 6 and publishing an update, we started seeing a large number of crashes in Firebase Crashlytics.
The crashes are triggered by NotificationCenter methods (post, addObserver, removeObserver) and show the following error:
BUG IN CLIENT OF LIBDISPATCH: Assertion failed: Block was expected to execute on queue [com.apple.main-thread (0x1f9dc1580)]
All scopes to related calls are already explicitly marked with @MainActor. This issue never occurred with Swift 5, but appeared immediately after moving to Swift 6.
Has anyone else encountered this problem? Is there a known solution or workaround?
Thanks in advance!
var testTwo: Double = 0
testDouble = 80
testTwo = 200
var testThree: Int = 0
testThree = Int(testTwo/testDouble)
var testDate: Date = .now
var dateComponent = DateComponents()
dateComponent.day = testThree
var newDate: Date = Calendar.current.date(byAdding: dateComponentwith a thread error , to: testDate)!
This code works in a playground. However, when I try to use it in Xcode for my app it fails with the following error:
Thread 1: Fatal error: Double value cannot be converted to Int because it is either infinite or NaN
I printed the value being converted to Int and it was not NAN or infinite.
Is there any way to retrieve the memory pressure percentage using native libraries?
When I run the memory-pressure command, I can see the percentage of free memory, but I’d like to retrieve the same information using a native library.
Topic:
Programming Languages
SubTopic:
Swift
I can't find any simple c++ xcodeproj call to swift struct using modern c++ swift mix. there is the fibonacci example that is swift app call to c++.
Base on fibonacci example I create new simple project and fail to build it with error when I try to include #include <SwiftMixTester/SwiftMixTester-Swift.h>
What is wrong?
Is it the right place to ask this?
Any work project link?
Xcode 26.
Topic:
Programming Languages
SubTopic:
Swift