我如何编写一个函数来接受任何符合 Codable 的对象
How can I write a function which accepts any object which conforms to Codable
func sendToServer(message: Codable) {
do {
let jsonData = try JSONEncoder().encode(message)
let jsonString = String(data: jsonData, encoding: .utf8)!
// send to server jsonString
} catch let error {
debugPrint("Error occured during parsing \(error.localizedDescription)")
}
}
我正在尝试创建一个方法来接受符合 Codable 的对象,但是当我尝试编码时出现此错误:
Cannot invoke 'encode' with an argument list of type '(Codable)'
如何编写实现此目的的方法?
您的签名不正确。你不想要 Codable。你想要一个符合 Codable 的泛型类型。具体来说,你只需要一个符合 Encodable 的:
func sendToServer<Message: Encodable>(message: Message) { ... }
A "Codable" 或 "Encodable"(协议)本身无法编码。它没有关于编码内容的任何信息。但是 符合 到 Encodable 的类型提供了该信息。
func sendToServer(message: Codable) {
do {
let jsonData = try JSONEncoder().encode(message)
let jsonString = String(data: jsonData, encoding: .utf8)!
// send to server jsonString
} catch let error {
debugPrint("Error occured during parsing \(error.localizedDescription)")
}
}
我正在尝试创建一个方法来接受符合 Codable 的对象,但是当我尝试编码时出现此错误:
Cannot invoke 'encode' with an argument list of type '(Codable)'
如何编写实现此目的的方法?
您的签名不正确。你不想要 Codable。你想要一个符合 Codable 的泛型类型。具体来说,你只需要一个符合 Encodable 的:
func sendToServer<Message: Encodable>(message: Message) { ... }
A "Codable" 或 "Encodable"(协议)本身无法编码。它没有关于编码内容的任何信息。但是 符合 到 Encodable 的类型提供了该信息。