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

Posts under Swift tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Extending @Model with custom macros
I am trying to extend my PersistedModels like so: @Versioned(3) @Model class MyType { var name: String init() { name = "hello" } } but it seems that SwiftData's@Model macro is unable to read the properties added by my @Versioned macro. I have tried changing the order and it ignores them regardless. version is not added to schemaMetadata and version needs to be persisted. I was planning on using this approach to add multiple capabilities to my model types. Is this possible to do with macros? VersionedMacro /// A macro that automatically implements VersionedModel protocol public struct VersionedMacro: MemberMacro, ExtensionMacro { // Member macro to add the stored property directly to the type public static func expansion( of node: AttributeSyntax, providingMembersOf declaration: some DeclGroupSyntax, in context: some MacroExpansionContext ) throws -> [DeclSyntax] { guard let argumentList = node.arguments?.as(LabeledExprListSyntax.self), let firstArgument = argumentList.first?.expression else { throw MacroExpansionErrorMessage("@Versioned requires a version number, e.g. @Versioned(3)") } let versionValue = firstArgument.description.trimmingCharacters(in: .whitespaces) // Add the stored property with the version value return [ "public private(set) var version: Int = \(raw: versionValue)" ] } // Extension macro to add static property public static func expansion( of node: SwiftSyntax.AttributeSyntax, attachedTo declaration: some SwiftSyntax.DeclGroupSyntax, providingExtensionsOf type: some SwiftSyntax.TypeSyntaxProtocol, conformingTo protocols: [SwiftSyntax.TypeSyntax], in context: some SwiftSyntaxMacros.MacroExpansionContext ) throws -> [SwiftSyntax.ExtensionDeclSyntax] { guard let argumentList = node.arguments?.as(LabeledExprListSyntax.self), let firstArgument = argumentList.first?.expression else { throw MacroExpansionErrorMessage("@Versioned requires a version number, e.g. @Versioned(3)") } let versionValue = firstArgument.description.trimmingCharacters(in: .whitespaces) // We need to explicitly add the conformance in the extension let ext = try ExtensionDeclSyntax("extension \(type): VersionedModel {}") .with(\.memberBlock.members, MemberBlockItemListSyntax { MemberBlockItemSyntax(decl: DeclSyntax( "public static var version: Int { \(raw: versionValue) }" )) }) return [ext] } } VersionedModel public protocol VersionedModel: PersistentModel { /// The version of this particular instance var version: Int { get } /// The type's current version static var version: Int { get } } Macro Expansion:
0
0
113
16h
Range For Keys and Values Of Dictionary
I came across a code let myFruitBasket = ["apple":"red", "banana": "yellow", "budbeeri": "dark voilet", "chikoo": "brown"] Can we have range for keys and values of dictionary, it will be convenient for keys print(myFruitBasket.keys[1...3]) // banana, budbeeri, chikoo same for values print(myFruitsBasket.values[1...3]) // yellow, voilet, brown
1
0
80
1d
fullscreencover Problem
Hello Apple Developer Community: I have a problem with the fullscreencover. I can see the Things, that shouldn’t be visible behind it. I’m currently developing with iOS 26 and only there it happens. I hope you can help me :) Have a nice day
0
0
12
1d
NSURLErrorDomain Code=-1003 ... again!
This happens when trying to connect to my development web server. The app works fine when connecting to my production server. The production server has a certificate purchased from a CA. My development web server has a locally generated certificate (from mkcert). I have dragged and dropped the rootCA.pem onto the Simulator, although it doesn't indicate it has been loaded the certificate does appear in the Settings app and is checked to be trusted. I have enabled "App Sandbox" and "Outgoing connections (Client)". I have tested the URL from my local browser which is working fine. What am I missing?
0
0
186
1d
coreml Fetching decryption key from server failed
My iOS app supports iOS 18, and I’m using an encrypted CoreML model secured with a key generated from Xcode. Every few months (around every 3 months), the encrypted model fails to load for both me and my users. When I investigate, I find this error: coreml Fetching decryption key from server failed: noEntryFound("No records found"). Make sure the encryption key was generated with correct team ID To temporarily fix it, I delete the old key, generate a new one, re-encrypt the model, and submit an app update. This resolves the issue, but only for a while. This is a terrible experience for users and obviously not a sustainable solution. I want to understand: Why is this happening? Is there a known expiration or invalidation policy for CoreML encryption keys? How can I prevent this issue permanently? Any insights or official guidance would be really appreciated.
5
1
335
1h
Custom Views in Picture-in-Picture Disappear When Starting Video Call in Another App on iOS 18
Hi Apple Developer Team, I'm encountering a regression in iOS 18 related to the Picture-in-Picture (PiP) feature when using custom views. In previous versions of iOS (up to iOS 17), it's possible to show a custom UIView inside the PiP window — for example, a UILabel, UITableView, or other standard UI elements. This works well even when switching between apps. However, in iOS 18 (tested on the developer beta), there's an issue: If App A starts PiP mode and displays a custom view, and then the user switches to App B and starts a video call (e.g., using FaceTime or another VoIP app), all the custom views in the PiP window suddenly disappear. The PiP window itself remains, but its contents are empty. This behavior did not occur in earlier iOS versions. Steps to reproduce: In App A, start Picture-in-Picture with a custom UIView added to the PiP window. Switch to App B and initiate a video call (e.g., FaceTime). Observe the PiP window — the custom view is no longer visible. This issue breaks UI functionality that previously worked and may impact apps that rely on interactive or dynamic content in PiP. Is this a known issue in iOS 18, or is this behavior change intentional? Any suggested workarounds or updates? Thanks in advance for your support.
0
0
14
1d
Why is SwiftUI so broken and not improving layered UI functionality
Again and and again, I reach the point in a new application where I need to make structural changes in components and my data model, and the SwiftUI compiler fails to compile and just reports "I'm lost in the weeds", with no indication of what it was last working on, aside from a particular level in a multi-layered nested UI. This typically happens when a sub-views construction is not coded correctly because I changed that view and am looking for what broke, by just letting the compiler tell me what is not compatible. This is how refactoring has been done for ages and it's just amazingly frustrating that Apple engineers don't seem to understand nor care about this issue enough to fix it. Why does this problem persist through version after version of SwiftUI? Is no-one actually using it for anything?
1
0
53
2d
What is the difference between .safeAreaInset and the new .safeAreaBar?
I've been trying out the new .safeAreaBar modifier for iOS 26, but I cannot seem to notice any difference between that and .safeAreaInset? The documentation says: the bar modifier configures the content to support views to automatically extend the edge effect of any scroll view’s the bar adjusts safe area of. But I can't seem to see that in action.
0
0
119
3d
Is it possible to pass the streaming output of Foundation Models down a function chain
I am writing a custom package wrapping Foundation Models which provides a chain-of-thought with intermittent self-evaluation among other things. At first I was designing this package with the command line in mind, but after seeing how well it augments the models and makes them more intelligent I wanted to try and build a SwiftUI wrapper around the package. When I started I was using synchronous generation rather than streaming, but to give the best user experience (as I've seen in the WWDC sessions) it is necessary to provide constant feedback to the user that something is happening. I have created a super simplified example of my setup so it's easier to understand. First, there is the Reasoning conversation item, which can be converted to an XML representation which is then fed back into the model (I've found XML works best for structured input) public typealias ConversationContext = XMLDocument extension ConversationContext { public func toPlainText() -> String { return xmlString(options: [.nodePrettyPrint]) } } /// Represents a reasoning item in a conversation, which includes a title and reasoning content. /// Reasoning items are used to provide detailed explanations or justifications for certain decisions or responses within a conversation. @Generable(description: "A reasoning item in a conversation, containing content and a title.") struct ConversationReasoningItem: ConversationItem { @Guide(description: "The content of the reasoning item, which is your thinking process or explanation") public var reasoningContent: String @Guide(description: "A short summary of the reasoning content, digestible in an interface.") public var title: String @Guide(description: "Indicates whether reasoning is complete") public var done: Bool } extension ConversationReasoningItem: ConversationContextProvider { public func toContext() -> ConversationContext { // <ReasoningItem title="${title}"> // ${reasoningContent} // </ReasoningItem> let root = XMLElement(name: "ReasoningItem") root.addAttribute(XMLNode.attribute(withName: "title", stringValue: title) as! XMLNode) root.stringValue = reasoningContent return ConversationContext(rootElement: root) } } Then there is the generator, which creates a reasoning item from a user query and previously generated items: struct ReasoningItemGenerator { var instructions: String { """ <omitted for brevity> """ } func generate(from input: (String, [ConversationReasoningItem])) async throws -> sending LanguageModelSession.ResponseStream<ConversationReasoningItem> { let session = LanguageModelSession(instructions: instructions) // build the context for the reasoning item out of the user's query and the previous reasoning items let userQuery = "User's query: \(input.0)" let reasoningItemsText = input.1.map { $0.toContext().toPlainText() }.joined(separator: "\n") let context = userQuery + "\n" + reasoningItemsText let reasoningItemResponse = try await session.streamResponse( to: context, generating: ConversationReasoningItem.self) return reasoningItemResponse } } I'm not sure if returning LanguageModelSession.ResponseStream<ConversationReasoningItem> is the right move, I am just trying to imitate what session.streamResponse returns. Then there is the orchestrator, which I can't figure out. It receives the streamed ConversationReasoningItems from the Generator and is responsible for streaming those to SwiftUI later and also for evaluating each reasoning item after it is complete to see if it needs to be regenerated (to keep the model on-track). I want the users of the orchestrator to receive partially generated reasoning items as they are being generated by the generator. Later, when they finish, if the evaluation passes, the item is kept, but if it fails, the reasoning item should be removed from the stream before a new one is generated. So in-flight reasoning items should be outputted aggresively. I really am having trouble figuring this out so if someone with more knowledge about asynchronous stuff in Swift, or- even better- someone who has worked on the Foundation Models framework could point me in the right direction, that would be awesome!
0
0
186
4d
sandbox causes the input method switch to fail to take effect
Dear Apple developers: Hello, recently I want to develop an application for macos that automatically switches input methods. The function is that when you switch applications, it can automatically switch to the input method you set, thus eliminating the trouble of manual switching. All the functions have been implemented, but only when the sandbox is closed. When I opened the sandbox, I found a very strange phenomenon. Suppose wechat was set to the Chinese input method. When I switched to wechat, wechat automatically got the focus of the input box. The input method icon in the upper right corner of the screen had actually switched successfully, but when I actually input, it was still the previous input method. If you switch to an application that does not have a built-in focus, the automatic switching of the input method will take effect when you click the input box with the mouse to regain the focus. This phenomenon is too difficult for my current technical level. I have tried many methods but none of them worked. I hope the respected experts can offer some ideas. Below is a snippet of the code switching I provided: DispatchQueue. Main. AsyncAfter (deadline: now () + 0.1) { let result = TISSelectInputSource(inputSource) if result == noErr { print(" Successfully switched to input method: \(targetInputMethod)") } else { print(" Input method switch failed. Error code: \(result)") } // Verify the switching result if let newInputSource = getCurrentInputSource() { print(" Switched input method: (newInputSource)") } } When the sandbox is opened, the synchronous switching does not take effect. The input method icon in the status bar will flash for a moment, unable to compete with system events. Even if it is set to DispatchQueue.main.async, it still does not work. It seems that there is a timing issue with the input method switching. Development environment macOS version: 15.4.1 Xcode version: 16.2
0
0
73
4d
Using @Environment for a router implementation...
Been messing with this for a while... And cannot figure things out... Have a basic router implemented... import Foundation import SwiftUI enum Route: Hashable { case profile(userID: String) case settings case someList case detail(id: String) } @Observable class Router { var path = NavigationPath() private var destinations: [Route] = [] var currentDestination: Route? { destinations.last } var navigationHistory: [Route] { destinations } func navigate(to destination: Route) { destinations.append(destination) path.append(destination) } } And have gotten this to work with very basic views as below... import SwiftUI struct ContentView: View { @State private var router = Router() var body: some View { NavigationStack(path: $router.path) { VStack { Button("Go to Profile") { router.navigate(to: .profile(userID: "user123")) } Button("Go to Settings") { router.navigate(to: .settings) } Button("Go to Listings") { router.navigate(to: .someList) } .navigationDestination(for: Route.self) { destination in destinationView(for: destination) } } } .environment(router) } @ViewBuilder private func destinationView(for destination: Route) -&gt; some View { switch destination { case .profile(let userID): ProfileView(userID: userID) case .settings: SettingsView() case .someList: SomeListofItemsView() case .detail(id: let id): ItemDetailView(id: id) } } } #Preview { ContentView() } I then have other views named ProfileView, SettingsView, SomeListofItemsView, and ItemDetailView.... Navigation works AWESOME from ContentView. Expanding this to SomeListofItemsView works as well... Allowing navigation to ItemDetailView, with one problem... I cannot figure out how to inject the Canvas with a router instance from the environment, so it will preview properly... (No idea if I said this correctly, but hopefully you know what I mean) import SwiftUI struct SomeListofItemsView: View { @Environment(Router.self) private var router var body: some View { VStack { Text("Some List of Items View") Button("Go to Item Details") { router.navigate(to: .detail(id: "Test Item from List")) } } } } //#Preview { // SomeListofItemsView() //} As you can see, the Preview is commented out. I know I need some sort of ".environment" added somewhere, but am hitting a wall on figuring out exactly how to do this. Everything works great starting from contentview (with the canvas)... previewing every screen you navigate to and such, but you cannot preview the List view directly. I am using this in a few other programs, but just getting frustrated not having the Canvas available to me to fine tune things... Especially when using navigation on almost all views... Any help would be appreciated.
2
0
213
5d
Tuple Comparision
I was trying to evaulate let myTuple = ("blue", false) let otherTuple = ("blue", true) if myTuple &lt; otherTuple { print("yes it evaluates") } Ans I got /tmp/S9jAk7P7KW/main.swift:5:12: error: binary operator '&lt;' cannot be applied to two '(String, Bool)' operands if myTuple &lt; 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
2
0
404
5d
Hang on retrieving StoreKit2 data in c++
I've been implementing in app purchases into an existing C++ app. I'm using the latest Swift StoreKit since the old ObjC interface is deprecated . There is a really weird problem where the swift/C++ bridging seems to get into a loop. After the Product structure is retrieved I have the following structure which I use to bridge to C++ public struct storeData { public var id : String public var displayName : String public var description : String public var price : String public var purchased : Bool = false public var level : Int = 0 } and this is passed back to the caller as follows public func getProducts (bridge : StoreBridge) -> [storeData] { bridge.products.sort { $0.price > $1.price } var productList : [storeData] = [] for product in bridge.products { let data : storeData = storeData(id: product.id, displayName: product.displayName, description: product.description, price: product.displayPrice, purchased: bridge.purchasedProductIds.contains(product.id) ) productList.append(data) } return productList } the "bridge" variable is a bridging class where the guts of the bridge resides, and contains the "products" array as a publishable variable. In the C++ code the data is retrieved by outProd->id = String(inProd.getId()); outProd->displayName = String(inProd.getDisplayName()); outProd->description = String(inProd.getDescription()); outProd->price = String(String(inProd.getPrice())); outProd->purchased = inProd.getPurchased(); The "String" is actually a JUCE string but that's not part of the problem. Testing this with a local StoreKit config file works fine but when I test with a sandbox AppStore the app hangs. Very specifically it hangs somewhere in the Swift thunk when retrieving the price. When I remove the line to retrieve the price everything works. And - and this is the weird bit - when I pad the price out with some random text, it now starts working (so I have a workaround). This is, however, slightly worrying behaviour. Ideas?
0
0
239
1w
iOS App'te Elektronik Sözleşme Onayı ve Hukuki Geçerlilik Süreci (KVKK - SwiftUI)
Merhaba, iOS üzerinde bir sözleşme onay uygulaması geliştiriyorum. Kullanıcıların dijital ortamda sözleşmeleri okuyup onaylaması gerekiyor. Ancak hukuki geçerlilik konusunda bazı tereddütlerim vardı. Bursa’da yaşayan biri olarak bu konuda bir avukata danışmam gerekti. Şans eseri https://www.avukatcanata.com ile karşılaştım ve hem bireysel hem ticari sözleşmeler konusunda gerçekten çok net açıklamalar sundular. Özellikle elektronik imza ve KVKK uyumu hakkında verdikleri bilgiler sayesinde projemi yasal zemine oturtabildim. Eğer bu tarz uygulamalar geliştiriyorsanız, mutlaka bir hukukçu görüşü alın. Yanlış bir adım size veya kullanıcınıza ciddi sonuçlar doğurabilir. Teşekkürler 🍏
0
0
16
1w