我目前正在构建一个框架,并希望使 SwiftUI 符合仅适用于 iOS 14Color
的RawRepresentable
协议。我有以下代码:
@available(iOS 14.0, *)
extension Color: RawRepresentable {
public init?(rawValue: Data) {
let uiColor = try? NSKeyedUnarchiver.unarchivedObject(ofClass: UIColor.self, from: rawValue)
if let uiColor = uiColor {
self = Color(uiColor)
} else {
return nil
}
}
public var rawValue: Data {
let uiColor = UIColor(self)
return (try? NSKeyedArchiver.archivedData(withRootObject: uiColor, requiringSecureCoding: false)) ?? Data()
}
}
但是,这会导致两个类似的错误:
Protocol 'RawRepresentable' requires 'init(rawValue:)' to be available in iOS 13.0.0 and newer
Protocol 'RawRepresentable' requires 'rawValue' to be available in iOS 13.0.0 and newer
这不可能吗?我可以将代码修改为:
extension Color: RawRepresentable {
public init?(rawValue: Data) {
let uiColor = try? NSKeyedUnarchiver.unarchivedObject(ofClass: UIColor.self, from: rawValue)
if let uiColor = uiColor {
self = Color(uiColor)
} else {
return nil
}
}
public var rawValue: Data {
if #available(iOS 14, *) {
let uiColor = UIColor(self)
return (try? NSKeyedArchiver.archivedData(withRootObject: uiColor, requiringSecureCoding: false)) ?? Data()
}
fatalError("do not use Color.rawValue on iOS 13")
}
}
这修复了错误,但调用fatalError
.
感谢您的任何帮助!