我目前正在构建一个框架,只想让SwiftUI Color符合iOS 14的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 newerProtocol '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似乎是错误的。
谢谢你的帮助!
发布于 2021-03-16 19:45:35
看起来Swift目前还没有正式(或完全)支持这个特性(Swift 5.3)。
您的代码可以简化为以下几行:
// for example: in project with minimum deploy target of iOS 13.0
struct A {}
protocol B {
var val: Int { get }
}
@available(iOS 14.0, *)
extension A: B {
var val: Int { // <- Compiler Error
0
}
}
// The compiler says: Protocol 'B' requires 'val' to be available in iOS 13.0.0 and newer.相关功能在Swift论坛上进行了讨论:https://forums.swift.org/t/availability-checking-for-protocol-conformances/42066。
希望当它在Swift 5.4 ( https://github.com/apple/swift/blob/main/CHANGELOG.md#swift-54)中落地时,你的问题就可以解决了。
https://stackoverflow.com/questions/66647798
复制相似问题