简体   繁体   English

如何创建具有可选泛型类型的动态结构

[英]how to create dynamic struct with optional generic type

I have created a Decodable base Struct for API response.我为 API 响应创建了一个可解码的基础结构。

struct ResponseBaseModel<T: Decodable>: Decodable {
    let status: Bool
    let message: String
    var result: T?

    private enum CodingKeys: String, CodingKey {
        case result, message, success,status,statusCode
    }

     init(from decoder: Decoder) throws {
           let values = try decoder.container(keyedBy: CodingKeys.self)
            if let result = try? values.decode(T.self, forKey: .result) {
                self.result = result
            }
        status = try  values.decode(Bool.self, forKey: .status)
        message = try  values.decode(String.self, forKey: .message)
       }
}

// here is API response // 这里是 API 响应

{
    "status": true,
    "statusCode": 200,
    "message": "Theater list successfully",
    "result": [
        {
            "id": 1,
            "name": "Galaxy",
            "picture": "https://ctdemo.workpc.online/kshatrainfotech/abol-app/public/storage/images/theaters/default.png",
            "is_notify": false
        }
    ]
}

here is how I use it for calling API这是我如何使用它来调用 API

 apimanager.fetch { [weak self] (response: Result<ResponseBaseModel<[Theater]>, ApiError>) in
        self?.handelResponse(response: response) { response in
            switch response {
            case .success(let theaterList):
                self?.theaterViewModels = theaterList.map{ TheaterViewModel(theaterModel: $0)}
                self?.responseHandler(.success(self!.theaterViewModels))
            case .failure(let apiError):
                self?.responseHandler(.failure(apiError))
            }
        }
    }

but some API doesn't have a result such as但某些 API 没有结果,例如

{ "status": true, "statusCode": 200, "message": "api.DATA_UPDATED_SUCCESS" } { "status": true, "statusCode": 200, "message": "api.DATA_UPDATED_SUCCESS" }

how to handle the above response with the ResponseBaseModel model.because I have to pass any type while working with ResponseBaseModel struct.如何使用 ResponseBaseModel 模型处理上述响应。因为在使用 ResponseBaseModel 结构时我必须传递任何类型。

ResponseBaseModel<?>

I already try ResponseBaseModel<nil> but it's not worked.我已经尝试过ResponseBaseModel<nil>但它没有用。

I try to simplyfy your question a little, to show why the thing you want is not possible this way.我试着稍微简化一下你的问题,以说明为什么你想要的东西不可能这样。 Think of the follwing structure:考虑以下结构:

struct TestStruct<T> {
    let code:Int
    var value:T?

    init(code:Int) {
        self.code = code
    }
} 

Typically you would use it this way:通常你会这样使用它:

var s = TestStruct<String>(code:42)
s.value = "abc"

print (s) // TestStruct<String>(code: 42, value: Optional("abc"))

Now you say: "Oh, I need a TestStruct only for some code, with no value at all" and try the following:现在你说:“哦,我只需要一个 TestStruct 用于一些代码,根本没有价值”并尝试以下操作:

var codeOnly = TestStruct<nil>(code:42)
print (codeOnly)

The compiler complains, because it needs a dedicated type for the value property.编译器抱怨,因为它需要一个专用的value属性类型。 Why doesn't it work?为什么不起作用? Because think of the following statement:因为想到以下语句:

let v = codeOnly.value
// or
codeOnly.value = "String"

Here, the compiler needs to know what type the property codeOnly.value is.在这里,编译器需要知道属性codeOnly.value是什么类型。 Since it cannot now, it will not allow a untyped TestStruct .由于它现在不能,因此它不允许无类型的TestStruct

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

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