0

我目前正在构建一个框架,并希望使 SwiftUI 符合仅适用于 iOS 14ColorRawRepresentable协议。我有以下代码:

@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.

感谢您的任何帮助!

4

1 回答 1

0

看来 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 ) 时,您的问题将得到解决。

于 2021-03-16T11:45:34.993 回答