如何使用@AppStorage 在 SwiftUI 中保存 UUID
How to save a UUID in SwiftUI using @AppStorage
使用时
@AppStorage("navigationWaypointID") var navigationWaypointID: UUID?
我得到一个No exact matches in call to initializer
。
我可以通过使用字符串和使用字符串作为真实来源的自定义 属性 来解决问题,但这并不理想。例如,
@AppStorage("selectedWaypointID") var selectedWaypointIDString: String?
var selectedWaypointID: UUID? {
get { UUID(uuidString: selectedWaypointIDString ?? "") }
set { selectedWaypointIDString = newValue?.uuidString }
}
我们可以确认 UUID
到 RawRepresentable
协议,因此它适合 AppStorage
初始化之一。
这是一个可能的方法。使用 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)
}
}
然后您的原始(下方)代码就可以正常工作 'as-is'
@AppStorage("navigationWaypointID") var navigationWaypointID: UUID?
使用时
@AppStorage("navigationWaypointID") var navigationWaypointID: UUID?
我得到一个No exact matches in call to initializer
。
我可以通过使用字符串和使用字符串作为真实来源的自定义 属性 来解决问题,但这并不理想。例如,
@AppStorage("selectedWaypointID") var selectedWaypointIDString: String?
var selectedWaypointID: UUID? {
get { UUID(uuidString: selectedWaypointIDString ?? "") }
set { selectedWaypointIDString = newValue?.uuidString }
}
我们可以确认 UUID
到 RawRepresentable
协议,因此它适合 AppStorage
初始化之一。
这是一个可能的方法。使用 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)
}
}
然后您的原始(下方)代码就可以正常工作 'as-is'
@AppStorage("navigationWaypointID") var navigationWaypointID: UUID?