Discuss Swift.

Swift Documentation

Posts under Swift subtopic

Post

Replies

Boosts

Views

Created

init?(coder: NSCoder) or init?(coder: (NSCoder?))
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 ?
2
0
86
5d
CarPlay CPListImageRowItem causes Inverted Scrolling and Side Button malfunction
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:
0
0
35
1d
CloudKit Sync Stalls During Initial Large Data Hydration on New Device (SwiftData Local-First Architecture)
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!
0
0
15
17h
Metal Shader inside Swift Package not found?
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.
0
0
17
16h