Gerry Shaw
Gerry Shaw

Reputation: 9378

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 }
}

Upvotes: 3

Views: 1258

Answers (1)

Asperi
Asperi

Reputation: 257779

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?

Upvotes: 12

Related Questions