'How to save a UUID in SwiftUI using @AppStorage
When using
@AppStorage("navigationWaypointID") var navigationWaypointID: UUID?
I get a No exact matches in call to initializer.
I can work around by using a String and a custom property that uses the string as the source of truth but that isn't ideal. E.g.,
@AppStorage("selectedWaypointID") var selectedWaypointIDString: String?
var selectedWaypointID: UUID? {
get { UUID(uuidString: selectedWaypointIDString ?? "") }
set { selectedWaypointIDString = newValue?.uuidString }
}
Solution 1:[1]
We can confirm UUID to RawRepresentable protocol so it fits to one of AppStorage init.
Here is a possible approach. Tested with Xcode 13.2 / iOS 15.2
extension UUID: RawRepresentable {
public var rawValue: String {
self.uuidString
}
public typealias RawValue = String
public init?(rawValue: RawValue) {
self.init(uuidString: rawValue)
}
}
and then your original (below) code just works 'as-is'
@AppStorage("navigationWaypointID") var navigationWaypointID: UUID?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
