iOS:如何对具有协议类型的变量的模型类使用可解码的代码

问题描述 投票:-1回答:1

问题:有一个符合Decodable的模型类,该模型的变量类型为someProtocol。但是编译器给出一个错误,

编译器错误

Type 'MyModel' does not conform to protocol 'Decodable'
Protocol requires initializer 'init(from:)' with type 'Decodable'
Cannot automatically synthesize 'Decodable' because 'SomeProtocol' does not conform to 
'Decodable'

代码段

class MyModel: Decodable {
var name: String?
var employee: SomeProtocol?

enum CodingKeys: String, CodingKey {
    case name
    case employee
}

} // Enf of class MyModel

protocol SomeProtocol {
 var employeeName: String ? { get }
}
swift swift-protocols decodable
1个回答
0
投票

[已解决]嗨,所以我想这个问题是有效的,经过一番搜索,我能够解决。MyModel类不能具有协议类型,应该有一个继承协议的具体类型类。现在,对象也与嵌套的其他模型对象一起被解码。

更正上面的代码

class MyModel: Decodable {
var name: String?
var employee: OtherModel?

enum CodingKeys: String, CodingKey {
case name = "DepartmentName"
case employee
}

} // End of class MyModel

class OtherModel: SomeProtocol {
var employeeName: String?
}

protocol SomeProtocol: Decodable {
 var employeeName: String? { get }
}

注:不需要init(来自解码器:Decoder)在这种情况下。

© www.soinside.com 2019 - 2024. All rights reserved.