简体   繁体   中英

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?' does not conform to 'Decodable' Protocol requires initializer 'init(from:)' with type 'Decodable'

Cannot automatically synthesize 'Decodable' because 'T?' does not conform to 'Encodable' Protocol requires initializer 'init(from:)' with type 'Encodable'

The issue is caused by the fact that you declared both properties of Response as implicitly unwrapped optionals (IOU). The compiler cannot autogenerate the required methods of Codable for IOU properties.

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 ! ).

Also, Swift is not Objective-C. There's no need to make your types inherit from NSObject . And you should also use struct s instead of class es unless you explicitly need reference type behaviour. 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)
        }
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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