Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save a UUID in SwiftUI using @AppStorage

Tags:

swiftui

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 }
}
like image 982
Gerry Shaw Avatar asked Nov 03 '25 10:11

Gerry Shaw


1 Answers

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?
like image 94
Asperi Avatar answered Nov 05 '25 00:11

Asperi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!