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

SwiftData fatal error: Failed to locate relationship for StringCodingKey
I'm experiencing a new error in SwiftData since updating to Xcode 16/iOS 17 DB1. When passing in a model (Student) to a view and then displaying an array of Points using ForEach, I get the following fatal error: SwiftData/ModelCoders.swift:2438: Fatal error: Failed to locate relationship for StringCodingKey(stringValue: "group", intValue: nil) on Entity - name: Point superentity: subentities: storedProperties: CompositeAttribute - name: type, options: [], valueType: PointType, defaultValue: nil Properties: Attribute - name: type, options: [], valueType: String, defaultValue: nil, hashModifier: nil Relationship - name: outcome, options: [], valueType: Outcome, destination: Outcome, inverseName: nil, inverseKeypath: nil CompositeAttribute - name: proficiency, options: [], valueType: Proficiency, defaultValue: nil Properties: Attribute - name: proficiency, options: [], valueType: String, defaultValue: nil, hashModifier: nil Attribute - name: date, options: [], valueType: Date, defaultValue: nil, hashModifier: nil Attribute - name: note, options: [], valueType: String, defaultValue: nil, hashModifier: nil Relationship - name: student, options: [], valueType: Optional<Student>, destination: Student, inverseName: points, inverseKeypath: Optional(\Student.points) Attribute - name: group, options: [], valueType: Array<PersistentIdentifier>, defaultValue: [], hashModifier: nil inheritedProperties: uniquenessConstraints: indices: Xcode flags this line of the macro-generated getter of the outcome property on Point: @storageRestrictions(accesses: _$backingData, initializes: _outcome) init(initialValue) { _$backingData.setValue(forKey: \.outcome, to: initialValue) _outcome = _SwiftDataNoType() } get { _$observationRegistrar.access(self, keyPath: \.outcome) return self.getValue(forKey: \.outcome) // Fatal error: Failed to locate relationship for StringCodingKey... } set { _$observationRegistrar.withMutation(of: self, keyPath: \.outcome) { self.setValue(forKey: \.outcome, to: newValue) } } This worked just fine in iOS 17. Here's a snippet of the Student implementation: @Model class Student: Identifiable, Comparable { var name: String var number: Int @Relationship(deleteRule: .cascade, inverse: \Point.student) var points: [Point] @Relationship(deleteRule: .cascade, inverse: \Mark.student) var marks: [Mark] @Relationship(deleteRule: .nullify, inverse: \StudentGroup.students) var groups: [StudentGroup] = [] var archived: Bool } and the implementation of Point: @Model class Point: Identifiable, Comparable { var student: Student? var type: PointType var outcome: Outcome var proficiency: Proficiency var group: [Student.ID] = [] var date: Date var note: String } and finally the implementation for Outcome: @Model class Outcome: Identifiable, Comparable { var name: String var index: Int var rubric: Rubric? var proficiencies: [Proficiency] } I've tried adding a relationship in Outcome as an inverse of the outcomes property on Points (although this does not make sense in my implementation, which is why I initially did not set a relationship here) and the problem persisted. Any ideas what this error means and how I might go about fixing it?
0
0
27
3h
TipKit vs. Swift 6 + Concurrency
I'm trying to convert my project to use Swift 6 with Complete Concurrency in Xcode 16 beta 1. The project uses TipKit, but I'm getting compile errors when trying to use the TipKit Parameters feature. Here is an example of the type of error I'm seeing (Note that this code from https://developer.apple.com/documentation/tipkit/highlightingappfeatureswithtipkit): struct ParameterRuleTip: Tip { // Define the app state you want to track. @Parameter static var isLoggedIn: Bool = false Static property '$isLoggedIn' is not concurrency-safe because it is non-isolated global shared mutable state. Is there a new pattern for supporting TipKit Parameters in Swift 6 with Complete Concurrency enabled? There is no obvious suggestion for how to fix this. The latest WWDC 2024 TipKit doesn't appear to have any solution(s).
0
0
26
4h
How to set up multi platform efficiently
Hello, so I have a SwiftUI app that is relatively large, and it has multiple targets, one for each platform. but as I near App Store release I'm feeling very confused as to how to configure it. One app was rejected because the Mac target's name becomes the app which is different from App Store (Texty+ [App Store] vs Texty+ Mac [on target]). So I then just combined all the files into one target with a #if os(Mac... iOS) etc, but is that the proper way for multi platform app. I know there is like a Multiplatform target but that would require I restructure all the files and that always leads to issues in this near release app.
0
0
19
4h
SwiftData History Tombstone Data is Unusable
After watching the WWDC video on the new history tracking in SwiftData, I started to update my app with this functionality. Unfortunately it seems that the current API in the first beta of Xcode 16 is rather useless in regards to tombstone data. The docs state that it would be possible to get the data from the tombstone by using a keyPath, there is no API for this however. The only thing I can do is iterate over the values (of type any) without any key information, so I do not know which data is what. Am I missing something or did we get a half finished implementation? There also does not seem to be any info on this in the release notes.
1
0
37
6h
SwiftData crashes on insert (Swift 6, Xcode 16, macOS 15)
I'm trying to insert values into my SwiftData container but it crashes on insert context.insert(fhirObject) and the only error I get from Xcode is: @Transient private var _hkID: _SwiftDataNoType? // original-source-range: /Users/cyril/Documents/GitHub/MyApp/MyApp/HealthKit/FHIR/FHIRModels.swift:35:20-35:20 configured as follows: import SwiftData import SwiftUI @main struct MyApp: App { var container: ModelContainer init() { do { let config = ModelConfiguration(cloudKitDatabase: .private("iCloud.com.author.MyApp")) container = try ModelContainer(for: FHIRObservation.self, configurations: config) UserData.shared = UserData(modelContainer: container) } catch { fatalError("Failed to configure SwiftData container.") } } var body: some Scene { WindowGroup { ContentView() .environmentObject(UserData.shared) } .modelContainer(container) } } My UserData and DataStore are configured as follows: import SwiftUI import SwiftData import os /// `FHIRDataStore` is an actor responsible for updating the SwiftData db as needed on the background thread. private actor FHIRDataStore { let logger = Logger( subsystem: "com.author.MyApp.FHIRDataStore", category: "ModelIO") private let container: ModelContainer init(container: ModelContainer) { self.container = container } func update(newObservations: [FHIRObservationWrapper], deletedObservations: [UUID]) async throws { let context = ModelContext(container) // [FHIRObservationWrapper] -> [FHIRObservation] // let modelUpdates = newObservations.lazy.map { sample in // FHIRObservation(hkID: sample.hkID, fhirID: sample.fhirID, name: sample.name, status: sample.status, code: sample.code, value: sample.value, range: sample.range, lastUpdated: sample.lastUpdated) // } do { try context.transaction { for sample in newObservations { let fhirObject = FHIRObservation(hkID: sample.hkID, fhirID: sample.fhirID, name: sample.name, status: sample.status, code: sample.code, value: sample.value, range: sample.range, lastUpdated: sample.lastUpdated) // App crashes here context.insert(fhirObject) } // for obj in modelUpdates { // // } // try context.delete(model: FHIRObservation.self, where: #Predicate { sample in // deletedObservations.contains(sample.hkID!) // }) // try context.save() logger.debug("Database updated successfully with new and deleted observations.") } } catch { logger.debug("Catch me bro: \(error.localizedDescription)") } } } @MainActor public class UserData: ObservableObject { let userDataLogger = Logger( subsystem: "com.author.MyApp.UserData", category: "Model") public static var shared: UserData! // MARK: - Properties public lazy var healthKitManager = HKManager(withModel: self) let modelContainer: ModelContainer private var store: FHIRDataStore init(modelContainer: ModelContainer) { self.modelContainer = modelContainer self.store = FHIRDataStore(container: modelContainer) } // MARK: - Methods func updateObservations(newObservations: [FHIRObservationWrapper], deletedObservations: [UUID]) { Task { do { try await store.update(newObservations: newObservations, deletedObservations: deletedObservations) userDataLogger.debug("Observations updated successfully.") } catch { userDataLogger.error("Failed to update observations: \(error.localizedDescription)") } } } } My @Model is configured as follows: public struct FHIRObservationWrapper: Sendable { let hkID: UUID let fhirID: String var name: String var status: String var code: FHIRCodeableConcept var value: FHIRLabValueType var range: FHIRLabRange? var lastUpdated: Date? } @Model public final class FHIRObservation { let hkID: UUID? let fhirID: String? @Attribute(.allowsCloudEncryption) var name: String? @Attribute(.allowsCloudEncryption) var status: String? @Attribute(.allowsCloudEncryption) var code: FHIRCodeableConcept? @Attribute(.allowsCloudEncryption) var value: FHIRLabValueType? @Attribute(.allowsCloudEncryption) var range: FHIRLabRange? @Attribute(.allowsCloudEncryption) var lastUpdated: Date? init(hkID: UUID?, fhirID: String?, name: String? = nil, status: String? = nil, code: FHIRCodeableConcept? = nil, value: FHIRLabValueType? = nil, range: FHIRLabRange? = nil, lastUpdated: Date? = nil) { self.hkID = hkID self.fhirID = fhirID self.name = name self.status = status self.code = code self.value = value self.range = range self.lastUpdated = lastUpdated } } Any help would be greatly appreciated!
2
0
85
1d
SwiftUI app runs differently on hardware platforms
I have a simple SwiftUI app that has a picker, textfield and several buttons. It is using a Enum as a focus state for the various controls. When I compile and run it on Mac Studio desktop it works as expected: Picker has initial focus, Selection in Picker changes focus to TextField, Tab key moves through buttons; last button resets to Picker However when I run the exact same app on MacBook Pro (same version of MacOS, 14.5) it does not work at all as expected. Instead: Initial focus is set to TextField, Tab does not change the focus, Clicking on last button resets focus to TextField rather than Picker The content view code: enum FFocus: Hashable { case pkNames case btnAssign case tfValue case btn1 case btn2 case noFocus } struct PZParm: Identifiable { var id = 0 var name = "" } struct ContentView: View { @State var psel:Int = 0 @State var tfVal = "Testing" @FocusState var hwFocus:FFocus? var body: some View { VStack { Text("Hardware Test").font(.title2) PPDefView(bSel: $psel) .focused($hwFocus, equals: .pkNames) TextField("testing", text:$tfVal) .frame(width: 400) .focused($hwFocus, equals: .tfValue) HStack { Button("Button1", action: {}) .frame(width: 150) .focused($hwFocus, equals: .btn1) Button("Button2", action: { tfVal = "" hwFocus = .tfValue }) .frame(width: 150) .focused($hwFocus, equals: .btn2) Button("New", action: { tfVal = "" hwFocus = .pkNames }) .frame(width: 150) .focused($hwFocus, equals: .btnAssign) } } .padding() // handle picker change .onChange(of: psel, { if psel > 0 {hwFocus = .tfValue} }) .onAppear(perform: {hwFocus = .pkNames}) } } #Preview { ContentView() } struct PPDefView: View { @Binding var bSel:Int // test defs let pzparms:[PZParm] = [ PZParm.init(id:1, name:"Name1"), PZParm.init(id:2, name:"Name2") ] // var body:some View { Picker(selection: $bSel, label: Text("Puzzle Type")) { ForEach(pzparms) {Text($0.name)} }.frame(width: 250) } }
2
0
99
3h
CommandGroup, Xcode 16b1, and Swift 6
I suspect this will be a "wait for the next beta" item, but thought I'd throw it out here in case anyone knows of a workaround. Mac app compiling under Xcode 16 beta 1. Trying to get rid of all warning that would stop the adoption of Swift 6 -- Strict Concurrency Checking is set to Complete. I'm down to one warning before I can enable swift 6. SwiftUI.Commands Main actor-isolated static method '_makeCommands(content:inputs:)' cannot be used to satisfy nonisolated protocol requirement; this is an error in the Swift 6 language mode That's because I've added menu commands to the app. It's very easy to reproduce. import SwiftUI @main struct CommandApp: App { var body: some Scene { WindowGroup { ContentView() } .commands { HelpCommand() } } } struct HelpCommand: Commands { var body: some Commands { CommandGroup(replacing: .help) { Button("Help me") { // } } } } The suggested fix is telling me what change I should make ot _makeCommands. At least that is how I'm reading it.
0
0
78
1d
App crashed with NSInvalidUnarchiveOperationException when run from different target and scheme.
Hi, I'm trying to create a new target duplicated from the main target (cdx_ios) called cdx-ios-dev02. I also made a new scheme called cdx-ios-dev02 It can be built just fine however when I run it, it crashed and it throws this exception: *** Terminating app due to uncaught exception 'NSInvalidUnarchiveOperationException', reason: '*** -[NSKeyedUnarchiver decodeObjectForKey:]: cannot decode object of class (cdx_ios.AuthObject) for key (root) because no class named "cdx_ios.AuthObject" was found; the class needs to be defined in source code or linked in from a library (ensure the class is part of the correct target). If the class was renamed, use setClassName:forClass: to add a class translation mapping to NSKeyedUnarchiver' This is the class: class AuthObject: NSObject, NSCoding { var accessT1: String = "" var t1Type: String = "bearer" var refreshT1: String = "" var expiresIn: Int = 0 var scope: String = "" var jti: String = "" init(accessT1: String = "", t1Type: String = "bearer", refreshT1: String = "", expiresIn: Int = 0, scope: String = "", jti: String = "") { self.accessT1 = accessT1 self.t1Type = t1Type self.refreshT1 = refreshT1 self.expiresIn = expiresIn self.scope = scope self.jti = jti } convenience init(dic: [String: Any]) { self.init() mapping(dic) } required convenience init(coder aDecoder: NSCoder) { let t1 = aDecoder.decodeObject(forKey: "accessT1") as? String ?? "" let t1Type = aDecoder.decodeObject(forKey: "t1Type") as? String ?? "" let refreshT1 = aDecoder.decodeObject(forKey: "refreshT1") as? String ?? "" let expiresIn = aDecoder.decodeInteger(forKey: "expiresIn") let scope = aDecoder.decodeObject(forKey: "scope") as? String ?? "" let jti = aDecoder.decodeObject(forKey: "jti") as? String ?? "" self.init( accessT1: t1, t1Type: t1Type, refreshT1: refreshT1, expiresIn: expiresIn, scope: scope, jti: jti ) } func mapping(_ dic: [String: Any]) { accessT1 = ParseUtil.dictionaryValue(dic, "access_token", "") t1Type = ParseUtil.dictionaryValue(dic, "token_type", "bearer") refreshT1 = ParseUtil.dictionaryValue(dic, "refresh_token", "") expiresIn = ParseUtil.dictionaryValue(dic, "expires_in", 0) scope = ParseUtil.dictionaryValue(dic, "scope", "") jti = ParseUtil.dictionaryValue(dic, "jti", "") } func encode(with nsCoder: NSCoder) { nsCoder.encode(accessT1, forKey: "accessT1") nsCoder.encode(t1Type, forKey: "t1Type") nsCoder.encode(refreshT1, forKey: "refreshT1") nsCoder.encode(expiresIn, forKey: "expiresIn") nsCoder.encode(scope, forKey: "scope") nsCoder.encode(jti, forKey: "jti") } } It worked fine on the original target, cdx-ios. Can anybody help me? Thank you.
2
0
61
1d
Are several Proximity and Beacon related libraries methods and properties deprectaed and now unusable in iOS 18 beta?
Hi, Please let me know iOS 18 beta have deprecated/ stopped support for which of the following: proximityUUID CLBeaconRegion (instancetype)initWithProximityUUID:(NSUUID *)proximityUUID identifier:(NSString *)identifier (void)startRangingBeaconsInRegion:(CLBeaconRegion *)region -startRangingBeaconsSatisfyingConstraint: , is this also deprecated in iOS 18 beta, since: CLBeaconIdentityConstraint is deprecated right? CLBeaconIdentityCondition is not supported in XCode 15.3. What should I do for this? Should I install XCode 16 beta? locationManager:didRangeBeacons:satisfyingConstraint: can we use it in iOS 18 beta, since, CLBeaconIdentityConstraint is deprecated? what is alternative startMonitoring(for:) is also deprecated in iOS 18 beta right? Also, can someone specify or create a documentation on how beaconing shall be monitored, ranged and locationManager delegate methods pertaining to beaconing to be used in iOS 18 beta?
1
0
63
2d
Offloading task from the cooperative thread pool
Hi, When using Swift Concurrency blocking tasks like file I/O, GPU work and networking can prevent forward moving progress and have the potential to exhaust the cooperative thread pool and under utilize the CPU. It's been recommended to offload these tasks from the cooperative thread pool. Is my understanding correct that the preferred way to do this is by creating async tasks via Dispatch or OperationQueue? And combining these with Continuations if a return value from the task is required? Or should I always be using Continuations in combination with Dispatch/OperationQueue? There are also Executors but the documentation seems a bit limited on how to use these. The new TaskExecutor is also only available on the latest beta's. My question is basically what is the recommend way to offload a task? Thanks!
0
0
55
2d
Swift 6 actor error in didReceiveRemoteNotification of UIApplicationDelegate
From Xcode 16.0 Beta I am getting the following error at didReceiveRemoteNotification of UIApplicationDelegate protocol: Non-sendable type '[AnyHashable : Any]' in parameter of the protocol requirement satisfied by main actor-isolated instance method 'application(_:didReceiveRemoteNotification:)' cannot cross actor boundary; this is an error in the Swift 6 language mode Generic struct 'Dictionary' does not conform to the 'Sendable' protocol (Swift.Dictionary) How can I fix this warning before moving to Swift 6 mode.
0
0
49
2d
Can I ignore safe area when resizing a window in macOS 15?
I am attempting to make a macOS app to show a large popup with no titlebar and a transparent background that spans the entire active display. Currently, I am attempting the last part, with the sizing. I used an example on the relevant developer documentation page. This is the code I am using in my App struct: @main struct MakeGoodChoicesApp: App { ... var body: some Scene { ... Window("Make Good Choices", id:"popup") { PopupWindowContentView() .ignoresSafeArea(.all) } .windowIdealPlacement {_, context in return WindowPlacement( x: context.defaultDisplay.bounds.minX, y: context.defaultDisplay.bounds.minY, width: context.defaultDisplay.bounds.width, height: context.defaultDisplay.bounds.height ) } } } When running my application and using some code to open the popup window, I get the following result: I would expect the window to expand past the safe area, but it seems as if macOS clamped the window's size down to inside the safe areas. I would appreciate any help, many thanks!
0
1
57
3d
Fix actor-isolated class is different from nonisolated subclass error
I'm trying to migrate my fairly large application to Swift Concurrency. I've have a class marked as @MainActor that sub-classes a 3rd party abstract class that is not migrated to Swift Concurrency. I get the following error: Main actor-isolated class 'MyClass' has different actor isolation from nonisolated superclass 'OtherAbstractClass'; this is an error in the Swift 6 language mode My class needs to be MainActor as it uses other code that is required to be on the MainActor. I can't see how to suppress this warning, I know as a guarantee that the abstract class will always be on the main thread so I need a way of telling the compiler that when I don't own the 3rd party code. import OtherAbstractModule @MainActor class MyClass: OtherAbstractClass { .... } How can I satisfy the compiler in this case?
1
0
112
3d
SwiftData Custom Datastore Docs and Implementation
I have watched the following WWDC 2024 sessions: What’s new in SwiftData Create a custom data store with SwiftData Platform State of the Union Now, I have an application that exposes a GraphQL API endpoint that's using PostgreSQL Server 16.3 database. Next, this API returns JSON to the client application (i.e. SwiftUI app). Furthermore, I have checked the current documentation and the above videos appear to be the best reference at this time. My proposed architecture looks like the following: SwiftUI <--> SwiftData <--> PostgreStoreConfiguration && PostgreStore TBD <--> GraphQL API <--> PostgreSQL Thus, I have the following questions: Are there plans to add common out-of-the-box data store implementations for PostgreSQL, Cassandra, Redis, and so on? Will it be possible to implement data stores built to use gRPC, GraphQL, REST, and others to name a few? Will there be more documentation on the actual creation of a custom data store because the current documentation provides a slim API reference? I look forward to your feedback regarding the SwiftData custom data stores.
1
0
123
3d
SIGABRT Signal 6 Abort trap
I got crash report for my mobile application private var _timedEvents: SynchronizedBarrier<[String: TimeInterval]> private var timedEvents: [String: TimeInterval] { get { _timedEvents.value } set { _timedEvents.value { $0 = newValue } } } func time(event: String) { let startTime = Date.now.timeIntervalSince1970 trackingQueue.async { [weak self, startTime, event] in guard let self else { return } var timedEvents = self.timedEvents timedEvents[event] = startTime self.timedEvents = timedEvents } } From the report, the crash is happening at _timedEvents.value { $0 = newValue } struct ReadWriteLock { private let concurentQueue: DispatchQueue init(label: String, qos: DispatchQoS = .utility) { let queue = DispatchQueue(label: label, qos: qos, attributes: .concurrent) self.init(queue: queue) } init(queue: DispatchQueue) { self.concurentQueue = queue } func read<T>(closure: () -> T) -> T { concurentQueue.sync { closure() } } func write<T>(closure: () throws -> T) rethrows -> T { try concurentQueue.sync(flags: .barrier) { try closure() } } } struct SynchronizedBarrier<Value> { private let lock: ReadWriteLock private var _value: Value init(_ value: Value, lock: ReadWriteLock = ReadWriteLock(queue: DispatchQueue(label: "com.example.SynchronizedBarrier", attributes: .concurrent))) { self.lock = lock self._value = value } var value: Value { lock.read { _value } } mutating func value<T>(execute task: (inout Value) throws -> T) rethrows -> T { try lock.write { try task(&_value) } } } What could be the reason for the crash? I have attached the crash report. Masked.crash
4
0
116
2d
Using Core Data with the Swift 6 language mode
I'm starting to work on updating my code for Swift 6. I have a number of pieces of code that look like this: private func updateModel() async throws { try await context.perform { [weak self] in // do some work } } After turning on strict concurrency checking, I get warnings on blocks like that saying "Sending 'self.context' risks causing data races; this is an error in the Swift 6 language mode." What's the best way for me to update this Core Data code to work with Swift 6?
2
0
193
3d