简体   繁体   中英

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. Eg,

@AppStorage("selectedWaypointID") var selectedWaypointIDString: String?
var selectedWaypointID: UUID? {
    get { UUID(uuidString: selectedWaypointIDString ?? "") }
    set { selectedWaypointIDString = newValue?.uuidString }
}

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM