Swift is a powerful and intuitive programming language for Apple platforms and beyond.

Posts under Swift tag

200 Posts

Post

Replies

Boosts

Views

Activity

Programming Languages Resources
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"
0
0
642
5d
Can't make buttons rectangular!
Ever since Xcode Version 26.0.1 I cannot for the life of me make my buttons rectangular. They are all capsule (or oval) shaped. My interface was designed for square buttons but no matter what I do the issue stays the same. This is what I have (it's fairly barebones but would have worked before I believe): @IBOutlet weak var PagesInterface: UIButton! override func viewDidLoad() { super.viewDidLoad() PagesInterface.layer.cornerRadius = 0 PagesInterface.layer.masksToBounds = true }
0
0
5
1h
App Rejected Under Guideline 4.3(a) - “Spam” for Unofficial Telegram Client with Unique Features
Hi everyone, I’m currently working on a project based on the Telegram iOS open-source code. My goal is to build an unofficial Telegram client with Telegram’s permission (they have publicly allowed third-party clients under their open-source license). My app includes unique new features and UI improvements that are not present in the official Telegram app. Essentially, it’s Telegram plus additional features — built from the official source, but extended significantly. However, when I try to submit my app to the App Store, Apple rejects the build under Guideline 4.3(a) - Design - Spam with this message: “We still noticed your app shares a similar binary, metadata, and/or concept as apps submitted to the App Store by other developers, with only minor differences. Submitting similar or repackaged apps is a form of spam that creates clutter and makes it difficult for users to discover new apps.” I completely understand Apple’s intent to prevent low-effort clones or spam apps. However, in my case, this is a legitimate open-source-based project with new and unique functionality. I’ve spent a lot of time designing new features and improving user experience — this is not just a rebrand. Has anyone else experienced this issue when submitting an app based on an open-source client (like Telegram)? Is there any recommended approach to help Apple differentiate my app as a distinct and valuable product? Any advice or guidance would be greatly appreciated! 🙏 — Additional Context: The app is based on Telegram’s open-source iOS client. The app includes new features and UI changes. It’s submitted under a different name, icon, and bundle ID. I’m happy to comply with any additional clarification Apple might need. Thanks in advance to anyone who can share insight or experiences with this kind of rejection.
1
0
38
1h
Resize Window Form After Loading
I am trying to resize a Window Form after it loads and have done quite a bit of searching for code to do it. Here is one code snippet that works to size the form during the design phase. self.view.window?.contentMinSize = CGSize(width: 1100, height: 310) I have tried code like below to increase the window size after the Form loads if let myWindow = self.view.window ?? NSApplication.shared.mainWindow { // Increase window size and position after it loads let newRect = NSRect(x: 100, y: 100, width: 1400, height: 900) } It seems that this code not only changes the Form size after loading, but also changes the size of the Form in Main.swift, which is something I don't want. I read elsewhere that I had to disable constraints to resize the Form, so I tried code below. let tableView = NSTableView() tableView.translatesAutoresizingMaskIntoConstraints = false let newRect = NSRect(x: 100, y: 0, width: 1100, height: 600) myWindow?.setFrame(newRect, display: true) That code did not seem to do anything as well. Also, the Form displays in the lower left of the screen. Note that main reason I want to resize the Form after loading is to keep it smaller during design development. The same goes for the NSTableView, which I have not gotten to yet.
0
0
61
9h
Navigation Bar animation upon Tab change
Hi. Since Xcode 16 and/or iOS 18.0 (I upgraded at the same time), I have an strange effect in the lower (let's say) 20% section of the Navigation Bar when changing to another tab, and this independently if large titles are used or not. Mentioned section is brighter or darker than the rest of the Navigation Bar background, depending on which background tint is used. This effect lasts about 0.3 seconds, but is clearly visible, quite disturbing and new as of Xcode 16 and/or iOS 18.0. I use the code below in AppDelegate to get a gradient coloured Navigation Bar background. let appearance = UINavigationBarAppearance() UINavigationBar.appearance().standardAppearance = appearance UINavigationBar.appearance().compactAppearance = appearance UINavigationBar.appearance().scrollEdgeAppearance = appearance UINavigationBar.appearance().compactScrollEdgeAppearance = appearance If I don't use above code., the background color is filled and without gradient. Subject effect doesn't show in this case. The effect basically looks like when changing tab, the new Navigation Bar background doesn't clear right away, and keeps the background from the previous Navigation Bar for 0.3 seconds before new one Navigation Bar background is rendered. I spent quite some time on changing every possible setting, in code as well as storyboard ... no success so far. Any ideas how to disable this undesired animation?
1
0
680
1d
iOS 26: FloatingBarContainerView overlapping the whole custom ViewController
Hi everyone: I'm experiencing an issue in iOS 26. I've implemented a custom ViewController. It's super simple to edit images with flip, crop, zoom in, and zoom out. My question is that it seems very strange to me. It works without problems in iOS 17.5 and iOS 18. However, when I try to run it with iOS 26, the entire ViewController seems disabled; it doesn't recognize touches or anything. When I checked the UI hierarchy, I saw a strange FloatingBarContainerView overlaying the entire ViewController. I searched the documentation for information about this view, but I couldn't find anything. Any help on how to hide or remove this view in iOS 26? This hasn't been implemented anywhere.
2
0
144
1d
Example of DNS Proxy Provider Network Extension
I am trying to setup a system-wide DNS-over-TLS for iOS that can be turned off and on from within the app, and I'm struggling with the implementation details. I've searched online, searched forums here, used ChatGPT, and I'm getting conflicting information or code that is simply wrong. I can't find example code that is valid and gets me moving forward. I think I need to use NEDNSProxyProvider via the NetworkExtension. Does that sound correct? I have NetworkExtension -> DNS Proxy Capability set in both the main app and the DNSProxy extension. Also, I want to make sure this is even possible without an MDM. I see conflicting information, some saying this is opened up, but things like https://developer.apple.com/documentation/Technotes/tn3134-network-extension-provider-deployment saying a device needs to be managed. How do private DNS apps do this without MDM? From some responses in the forums it sounds like we need to parse the DNS requests that come in to the handleNewFlow function. Is there good sample code for this parsing? I saw some helpful information from Eskimo (for instance https://developer.apple.com/forums/thread/723831 ) and Matt Eaton ( https://developer.apple.com/forums/thread/665480 )but I'm still confused. So, if I have a DoT URL, is there good sample code somewhere for what startProxy, stopProxy, and handleNewFlow might look like? And valid code to call it from the main app?
10
0
184
1d
StoreKit Products Load After Rebuild But Not on Fresh Install (iOS/SwiftUI)
Problem: I'm implementing StoreKit 2 in my SwiftUI app. Products load successfully when I rebuild in Xcode, but on a fresh install, Product.products(for:) returns an empty array. The paywall shows "Unable to load pricing." Setup: Using StoreKit Configuration File ( .storekit ) for testing Product IDs match exactly between config and code: com..premium.lifetime (non-consumable) com..premium.monthly (auto-renewable subscription) com.****.premium.yearly (auto-renewable subscription) StoreKitManager is a @MainActor singleton with @Published properties What I've Tried: Initial delay before loading - Added 1-second delay in init before calling loadProducts() Product ID verification - Confirmed IDs match exactly between StoreKitConfig.storekit and code Retry logic with exponential backoff - Implemented 3 retry attempts with 0.5s/1s/1.5s delays Multiple calls to updatePurchasedProducts() - Called twice after initial load Verified StoreKit configuration - File is properly added to project, has valid product definitions Code Structure: swift @MainActor final class StoreKitManager: ObservableObject { static let shared = StoreKitManager() @Published private(set) var products: [Product] = [] private init() { updateListenerTask = listenForTransactions() Task { try? await Task.sleep(nanoseconds: 1_000_000_000) await loadProducts() // Returns empty on fresh install await updatePurchasedProducts() } } } Observations: ✅ Works perfectly after Xcode rebuild ❌ Fails on fresh app install (simulator & device) ❌ Product.products(for:) returns empty array (no error thrown) ✅ StoreKit configuration file is valid and properly configured Question: Why does StoreKit need a rebuild to recognize products? Is there a proper initialization sequence I'm missing for fresh installs? Environment: Xcode [Version 26.0 beta 7] iOS [IOS +17.0] Testing with StoreKit Configuration File
0
0
47
3d
Why does AppStore.requestReview(in:) require NSViewController Parameter?
Looking to update one of my apps that uses SKStoreReviewController +requestReview (deprecated) to AppStore.requestReview(in:) umm...I have a few of questions... Why is an NSViewController parameter required? It's really not so uncommon for an AppKit app to just use NSWindowController with a window that does not use NSViewController... It should be possible to present the review request in a standalone alert (attached to a window is preferred IMO but it still should be possible to ask in separate window). 3)...why Swift..(err nevermind) Ideally: AppStore requestReview should take a NSWindow parameter but that parameter should be optional. If nil the request should be presented in a standalone window (like an alert). If non nil..present as a sheet on the window. Why a view controller? Maybe I'm missing something.
2
0
70
5d
ManipulationComponent Not Translating using indirect input
When using the new RealityKit Manipulation Component on Entities, indirect input will never translate the entity - no matter what settings are applied. Direct manipulation works as expected for both translation and rotation. Is this intended behaviour? This is different from how indirect manipulation works on Model3D. How else can we get translation from this component? visionOS 26 Beta 2 Build from macOS 26 Beta 2 and Xcode 26 Beta 2 Attached is replicable sample code, I have tried this in other projects with the same results. var body: some View { RealityView { content in // Add the initial RealityKit content if let immersiveContentEntity = try? await Entity(named: "MovieFilmReel", in: reelRCPBundle) { ManipulationComponent.configureEntity(immersiveContentEntity, allowedInputTypes: .all, collisionShapes: [ShapeResource.generateBox(width: 0.2, height: 0.2, depth: 0.2)]) immersiveContentEntity.position.y = 1 immersiveContentEntity.position.z = -0.5 var mc = ManipulationComponent() mc.releaseBehavior = .stay immersiveContentEntity.components.set(mc) content.add(immersiveContentEntity) } } }
9
2
699
6d
SwiftUI Controls Documentation
Hi, I am looking for comprehensive "controls" documentation for SwiftUI. When searching on the Apple site, I have not seen any documentation that shows a picture of a control and an explantation of what it does, for all the available controls. I have also searched the web for such documentation, and have not found any. When I was learning Rust, I came across a beautiful document about GTK3 (PDF) that had a complete list of controls, including pictures. If something looked interesting I could do a search for more details. Thanks, Jim
1
0
120
6d
How can I render a ScrollView so that its ScrollPosition is at the correct ID during layout?
Below you will find an example view of my problem. It has one button that, when pressed, will toggle between two scroll views using withAnimation, setting the scroll position onto the 2nd and 3rd items for either scroll view in onAppear. The intent is to have the background of items within each list transition smoothly from their position in one list, to their position in the other. However, this does not appear to be easily possible when setting the list position using an ID/ScrollPosition: Initializing a ScrollPosition with the correct ID and rendering the ScrollView with that appears to have no effect - the ScrollView will be drawn at the top of the scroll contents The only way I've found to render the ScrollView at an ID position is to scroll to that position in onAppear. However, it appears that when doing so, the matchedGeometryEffect interpolates the position of the elements as if the contentOffset.y of the ScrollView is briefly 0, resulting in a strange effect The desired animation can be seen if the two lists are toggled rapidly, allowing for the matchedGeometryEffect to smooth out the brief y 0 and interpolate between the correct positions It seems I either need to a) ensure the list is laid out at the correct y location beforehand (very difficult with dynamic list items, but seems to solve this problem if setting the y position explicitly) b) ensure that the list is laid out at the correct ID beforehand (have not been able to figure out how) c) ensure the matched geometry effect animation ignores the brief "0" y offset of the ScrollView before setting the ID position in onAppear (have not been able to figure out how) Note that I have to use VStack here for the matched geometry effect to work consistently. Any ideas on solving this? Code: import SwiftUI struct Item: Identifiable { let id = UUID().uuidString var height: CGFloat var label: String } enum TestScrollListStyle { case primary case alternate } struct TestScrollList: View { let items: [Item] let style: TestScrollListStyle let namespace: Namespace.ID @Binding var scrollPosition: ScrollPosition var initialIndex: Int = 2 var body: some View { ScrollView { VStack(spacing: style == .primary ? 8 : 16) { ForEach(items, id: \.id) { item in switch style { case .primary: Text(item.label) .frame(maxWidth: .infinity) .frame(height: item.height) .padding(.horizontal) .background( Rectangle() .fill(.blue.opacity(0.15)) .matchedGeometryEffect(id: item.id, in: namespace) ) case .alternate: HStack { Circle() .fill(.green.opacity(0.25)) .frame(width: 24, height: 24) Text(item.label) .frame(maxWidth: .infinity, alignment: .leading) } .frame(height: item.height) .padding(.horizontal) .background( Rectangle() .fill(.green.opacity(0.08)) .matchedGeometryEffect(id: item.id, in: namespace) ) } } } .scrollTargetLayout() .padding(.vertical) } .scrollPosition($scrollPosition, anchor: .top) .onAppear { var tx = Transaction() tx.disablesAnimations = true withTransaction(tx) { if items.indices.contains(initialIndex) { scrollPosition.scrollTo(id: items[initialIndex].id) } } } } } struct ContentView: View { @Namespace private var matchedNamespace @State private var items: [Item] = (0..<10).map { i in Item(height: .random(in: 80...220), label: "Row \(i)") } @State private var showAlternateView: Bool = false // Scroll positions for each scroll view @State private var primaryScrollPosition = ScrollPosition(idType: String.self) @State private var alternateScrollPosition = ScrollPosition(idType: String.self) var body: some View { NavigationStack { ZStack { if !showAlternateView { TestScrollList( items: items, style: .primary, namespace: matchedNamespace, scrollPosition: $primaryScrollPosition, initialIndex: 2 ) } if showAlternateView { TestScrollList( items: items, style: .alternate, namespace: matchedNamespace, scrollPosition: $alternateScrollPosition, initialIndex: 3 ) } } .navigationTitle("Two ScrollViews + Matched Geometry") .toolbar { ToolbarItem(placement: .topBarTrailing) { Button(showAlternateView ? "Primary" : "Alternate") { withAnimation() { showAlternateView.toggle() } } } } } } } #Preview { ContentView() }
1
0
37
1w
preferredImageDynamicRange is not marked as being available only for iOS 17 and above.
open var isAnimating: Bool { get } /// The preferred treatment to use for HDR images. By default the image view will defer to the value from its traitCollection. open var preferredImageDynamicRange: UIImage.DynamicRange /// The resolved treatment to use for HDR images. open var imageDynamicRange: UIImage.DynamicRange { get } This attribute is not marked as being applicable only in iOS 17+ versions. When viewing the UIImageView code in Xcode, the @available(iOS 17.0, *) annotation was not added, which resulted in successful compilation but caused a crash on iOS 16 devices.
3
0
75
1w
Core Data + CKSyncEngine with Swift 6 — concurrency, Sendable, and best practices validation
Hi everyone, I’ve been working on migrating my app (SwimTimes, which helps swimmers track their times) to use Core Data + CKSyncEngine with Swift 6. After many iterations, forum searches, and experimentation, I’ve created a focused sample project that demonstrates the architecture I’m using. The good news: 👉 I believe the crashes I was experiencing are now solved, and the sync behavior is working correctly. 👉 The demo project compiles and runs cleanly with Swift 6. However, before adopting this as the final architecture, I’d like to ask the community (and hopefully Apple engineers) to validate a few critical points, especially regarding Swift 6 concurrency and Core Data contexts. Architecture Overview Persistence layer: Persistence.swift sets up the Core Data stack with a main viewContext and a background context for CKSyncEngine. Repositories: All Core Data access is abstracted into repository classes (UsersRepository, SwimTimesRepository), with async/await methods. SyncEngine: Wraps CKSyncEngine, handles system fields, sync tokens, and bridging between Core Data entities and CloudKit records. ViewModels: Marked @MainActor, exposing @Published arrays for SwiftUI. They never touch Core Data directly, only via repositories. UI: Simple SwiftUI views bound to the ViewModels. Entities: UserEntity → represents swimmers. SwimTimeEntity → times linked to a user (1-to-many). Current Status The project works and syncs across devices. But there are two open concerns I’d like validated: Concurrency & Memory Safety Am I correctly separating viewContext (main/UI) vs. background context (used by CKSyncEngine)? Could there still be hidden risks of race conditions or memory crashes that I’m not catching? Swift 6 Sendable Compliance Currently, I still need @unchecked Sendable in the SyncEngine and repository layers. What is the recommended way to fully remove these workarounds and make the code safe under Swift 6’s stricter concurrency rules? Request Please review this sample project and confirm whether the concurrency model is correct. Suggest how I can remove the @unchecked Sendable annotations safely. Any additional code improvements or best practices would also be very welcome — the intention is to share this as a community resource. I believe once finalized, this could serve as a good reference demo for Core Data + CKSyncEngine + Swift 6, helping others migrate safely. Environment iOS 18.5 Xcode 16.4 macOS 15.6 Swift 6 Sample Project Here is the full sample project on GitHub: 👉 [https://github.com/jarnaez728/coredata-cksyncengine-swift6] Thanks a lot for your time and for any insights! Best regards, Javier Arnáez de Pedro
3
0
386
1w
How To Position Controls With SwiftUI
I am coming from C#, where Forms and Controls are placed similar to Swift Storyboards. I have been trying to learn Storyboards, but keep running across tutorials regarding SwiftUI, and Storyboard examples are few. So the question becomes, "how do I position controls on a Form using SwiftUI?" See the example below. I have run across many videos that use either horizontal or vertical positioning of controls, but these examples are usually very simple, with items occupying only the center portion of the screen. I get stuck on examples that are more complicated. The example below only shows the controls for the upper part of a Form, with some type of textbox (Viewform) below making up the rest of the Form. How does one make more complicated placement of controls with SwiftUI?
10
0
342
1w
IPad OS 16.1, Playgrounds and input fields
I have installed the latest beta on my iPad , iPadOS 16.1 (20B5050f) On running in app in Playgrounds that has a TextField, external keyboard input do not seem to be working. Tapping on the Text field inserts the cursor but no text can be entered on my external keyboard. (TextEditor field also do not work) Tested with both a Smart Keyboard and a Magic Keyboard. The keyboard works to enter the code in playgrounds, so it is not a keyboard connection issue. Disconnecting the keyboard, the onscreen keyboard is displayed and works correctly. Is this a Playgrounds issue or an iPadOS 16.1 issue or a compatibility issue with Playgrounds & iPadOS 16.1 ? import SwiftUI struct ContentView: View {     @State var field: String = "Test input"          var body: some View {         VStack {             Image(systemName: "globe")                 .imageScale(.large)                 .foregroundColor(.accentColor)             Text("Hello, world!")             TextField("", text: $field)                 .frame(height: 100)         }     } }
3
0
1.6k
1w