Den*_*lko 35 serialization protocols ios swift codable
我设法让JSON和plist编码和解码都工作,但只能通过直接调用特定对象上的编码/解码函数.
例如:
struct Test: Codable {
var someString: String?
}
let testItem = Test()
testItem.someString = "abc"
let result = try JSONEncoder().encode(testItem)
Run Code Online (Sandbox Code Playgroud)
这很好,没有问题.
但是,我试图获得一个只接受Codable协议一致性类型的函数并保存该对象.
func saveObject(_ object: Encodable, at location: String) {
// Some code
let data = try JSONEncoder().encode(object)
// Some more code
}
Run Code Online (Sandbox Code Playgroud)
这会导致以下错误:
无法使用类型'(Encodable)'的参数列表调用'encode'
看看编码函数的定义,似乎它应该能够接受Encodable,除非Value是一些我不知道的奇怪类型.
open func encode<Value>(_ value: Value) throws -> Data where Value : Encodable
Run Code Online (Sandbox Code Playgroud)
vad*_*ian 64
使用约束的泛型类型 Encodable
func saveObject<T : Encodable>(_ object: T, at location: String) {
//Some code
let data = try JSONEncoder().encode(object)
//Some more code
}
Run Code Online (Sandbox Code Playgroud)