协议"RawRepresentable"要求"init(rawValue:)"在iOS 13.0.0及更高版本中可用



我目前正在构建一个框架,并希望使SwiftUIColor符合仅适用于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 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似乎是错误的。

谢谢你的帮助!

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(,你的问题就会得到解决。

相关内容

  • 没有找到相关文章

最新更新