下面的代碼無法編譯:斯威夫特4 JSONDecoder解碼協議類型
public protocol Foo: Decodable {
var message: String { get }
}
struct Bar: Foo {
let message: String
}
// the type conforming Foo protocol is passed from somewhere
let type: Foo.Type = Bar.self
decode(type: type, from: Data())
func decode<T>(type: T.Type, from data: Data) Where T: Decodable {
let decoder = JSONDecoder()
try! decoder.decode(type, from: data)
}
它拋出的錯誤: Cannot invoke 'decode' with an argument list of type '(Foo.Type, from: Data)'
。你們有什麼想法?
我需要約束的參數到這樣的協議:'func decode(type:T,from data:Data){讓解碼器= JSONDecoder() 試試! decode.decode(類型,來自:data) }' –
3stud1ant3
@ 3stud1ant3'decode(type:Bar.self,from:data)'throws'無法用類型爲'(T,from:Data)的參數列表調用'decode' )'' – akabc
'JSONEncoder' /'JSONDecoder'預計具體的類型,你不能使用協議類型。 – vadian