简体   繁体   English

类型“响应”不符合协议“可解码”\“可编码”

[英]Type 'Response' does not conform to protocol 'Decodable' \ 'Encodable'

class ErrorObj: NSObject,Codable {
    var numError:Int = 0
    var DescriptionError = ""
}

class Response<T: Codable>: NSObject, Codable { 
    var error:ErrorObj!
    var result:T!
    
    
    func getResponse(errorObj:(ErrorObj)->Void,sucssesObj:(T)->Void) {
        if error.numError != 0 {
            errorObj(error)
        } else{
            sucssesObj(result)
        }
    }
    
}

errors:错误:

Cannot automatically synthesize 'Decodable' because 'T?'无法自动合成“Decodable”,因为“T?” does not conform to 'Decodable' Protocol requires initializer 'init(from:)' with type 'Decodable'不符合 'Decodable' 协议需要初始化器 'init(from:)' 类型为 'Decodable'

Cannot automatically synthesize 'Decodable' because 'T?'无法自动合成“Decodable”,因为“T?” does not conform to 'Encodable' Protocol requires initializer 'init(from:)' with type 'Encodable'不符合 'Encodable' 协议需要初始化器 'init(from:)' 类型为 'Encodable'

The issue is caused by the fact that you declared both properties of Response as implicitly unwrapped optionals (IOU).该问题是由于您将Response的两个属性都声明为隐式解包选项 (IOU) 而引起的。 The compiler cannot autogenerate the required methods of Codable for IOU properties.编译器无法为 IOU 属性自动生成Codable所需的方法。

However, there's no need to make those IOU anyways.但是,无论如何都没有必要制作这些借据。 If they are required properties that are always present in the response, make them non-optional.如果它们是响应中始终存在的必需属性,请将它们设为非可选。 If they might be missing, make them Optional (use ? instead of ! ).如果它们可能丢失,请将它们设为Optional (使用?而不是! )。

Also, Swift is not Objective-C.此外,Swift 不是 Objective-C。 There's no need to make your types inherit from NSObject .没有必要让你的类型继承自NSObject And you should also use struct s instead of class es unless you explicitly need reference type behaviour.除非您明确需要引用类型行为,否则您还应该使用struct s 而不是class es。 You should also make all properties immutable unless you explicitly need to be able to mutate them.您还应该使所有属性不可变,除非您明确需要能够改变它们。

struct ErrorObj: Codable {
    let numError: Int
    let description: String
}

struct Response<T: Codable>: Codable {
    let error: ErrorObj
    let result: T

    func getResponse(errorObj: (ErrorObj) -> Void, successObj: (T) -> Void) {
        if error.numError != 0 {
            errorObj(error)
        } else{
            successObj(result)
        }
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM