Here is my code:
import Foundation
import Combine
func todo() -> Never{ fatalError("Not Implemented!") }
protocol WASMDecodable{
init(from decoder: WASMDecoder) throws
}
protocol WASMLeafDecodable: WASMDecodable{}
extension WASMLeafDecodable{
init(from decoder: any WASMDecoder) throws { self = try decoder.decode(Self.self) }
}
protocol WASMTopLevelDecoder{
associatedtype Input
func decode<T: WASMDecodable>(_ type: T.Type, from input: Self.Input) throws -> T
}
protocol WASMDecoder{
func decode<T: WASMDecodable>(_ type: T.Type) throws -> T
func decode(_ type: UInt8.Type) throws -> UInt8
}
extension WASMDecoder{
}
class WASMBinaryContainer: WASMDecoder{
func decode(_ type: UInt8.Type) throws -> UInt8 {
todo()
}
func decode<T>(_ type: T.Type) throws -> T where T : WASMDecodable {
try T(from: self)
}
}
class WASMBinaryDecoder: WASMTopLevelDecoder{
func decode<T>(_ type: T.Type = T.self, from input: Data) throws -> T where T : WASMDecodable {
try WASMBinaryContainer(bytes: input).decode(type)
}
}
extension UInt8: WASMLeafDecodable{ }
let a: UInt8 = try WASMBinaryDecoder().decode(from: Data([0x01, 0x02]))
The compiler always chose to call the func decode<T>(_ type: T.Type) throws -> T where T : WASMDecodable
instead of non-generic one.
Is there a way to let it choose to call the non-generic one.
I try to modify the non-generic one to this:
func decode<T: WASMDecodable>(_ type: T.Type) throws -> T where T == UInt8
But it will only spit out a warning that says this will be an error in swift 6, and will not affect the compiler’s choice.
赵家辉 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.