gpt4 book ai didi

swift - 条件协议(protocol)一致性 : Cannot convert value of type 'Array<_>' to specified type '[UInt8]'

转载 作者:行者123 更新时间:2023-11-28 05:54:07 26 4
gpt4 key购买 nike

尝试使用条件一致性在 Swift 4.1 中扩展数组、字符串和字典,但在尝试使用符合 Decodable 的 Element 初始化数组时遇到了死胡同/Encodable 通过名为 BinaryCodable 的自定义协议(protocol)。

以下摘自https://github.com/mikeash/BinaryCoder但已进行调整以使用 Swift 的新条件一致性以使其能够编译。

extension Array: BinaryCodable where Element: BinaryDecodable, Element: BinaryEncodable {
public func binaryEncode(to encoder: BinaryEncoder) throws {
try encoder.encode(self.count)
for element in self {
try element.encode(to: encoder)
}
}

public init(fromBinary decoder: BinaryDecoder) throws {
let binaryElement = Element.self

let count = try decoder.decode(Int.self)
self.init()
self.reserveCapacity(count)
for _ in 0 ..< count {
let decoded = try binaryElement.init(from: decoder)
self.append(decoded)
}
}
}

extension String: BinaryCodable {
public func binaryEncode(to encoder: BinaryEncoder) throws {
try (Array(self.utf8) as! BinaryCodable).binaryEncode(to: encoder)
}

public init(fromBinary decoder: BinaryDecoder) throws {
let utf8: [UInt8] = try Array(fromBinary: decoder)
if let str = String(bytes: utf8, encoding: .utf8) {
self = str
} else {
throw BinaryDecoder.Error.invalidUTF8(utf8)
}
}
}

但是,我得到:

Cannot convert value of type 'Array<_>' to specified type '[UInt8]'

对于这一行:

let utf8: [UInt8] = try Array(fromBinary: decoder)

如有任何帮助,我们将不胜感激。

最佳答案

为了Array<UInt8>成为BinaryCodable , 它的元素类型 UInt8必须是 BinaryCodable ,事实并非如此。该协议(protocol)有其所需方法的默认实现,但一致性必须仍然明确声明:

extension UInt8: BinaryCodable {}

然后是你的extension String编译,你甚至可以摆脱强制转换as! BinaryCodable在里面编码方法(并使用 guard 允许节省一行):

extension String: BinaryCodable {
public func binaryEncode(to encoder: BinaryEncoder) throws {
try Array(self.utf8).binaryEncode(to: encoder)
}

public init(fromBinary decoder: BinaryDecoder) throws {
let utf8: [UInt8] = try Array(fromBinary: decoder)
guard let str = String(bytes: utf8, encoding: .utf8) else {
throw BinaryDecoder.Error.invalidUTF8(utf8)
}
self = str
}
}

关于swift - 条件协议(protocol)一致性 : Cannot convert value of type 'Array<_>' to specified type '[UInt8]' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51977931/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com